Computers/Language java

week10. Inheritance

emzei 2011. 4. 10. 19:55

 Inheritance 

1 class - 1 extend 


 Inheritance Hierarchies

- Set of classes con form an inheritance hierarchy

* Classes representing the most general concepts are near the root, more specialized classes towards the branches :




◇ Superclass : more general class

◇ Subclass : more specialized class that inherits from the superclass


◇ Inheritance is a mechanism for extending existing classes by adding instance variables and methods

◇ A subclass inherits the methods of its superclass

◇ In subclass, specify added instance variables, added methods, and changed or overriden methods:

◇ Instance variables declared in the superclass are present in subclass objects

◇ A subclass has no access to private instance variables of its superclass

◇ Encapsulation 

◇ Inheriting from a class differs from implementing an interface : 

   the subclass inherits behavior from the superclass


◐ Syntax - Inheritance


class SubclassName extends SuperclassName

{

     instance variables

     method

}


◐ Common Error : Shadowing Instance Variables

- A subclass has no access to the private instance variables of the superclass :

 public class SavingsAccount extends BankAccount

{

   public void addInterest()

   {

      double interest = getBalance() * interestRate / 100;

      balance = balance + interest; // Error

   }

   . . .

}


- Beginner's error : "solve" this problem by adding another instance variable with same name :


public class SavingsAccount extends BankAccount

{

   private double balance; // Don’t

   public void addInterest()

   {

      double interest = getBalance() * interestRate / 100;

      balance = balance + interest; // Compiles but doesn’t

         // update the correct balance

   }

   . . .

}

 





 Overriding Methods

- A subclass method overrides a superclass method if it has the same name and parameter types as a superclass method

* When such a method is applied to a subclass object, the overriding method is executed


◐ Calling a Superclass Method

super.methodName(parameter);

   EX)

public void deposit(double amount)

{

         transactionCount++;

         super.deposit(amount);

         // Calls the method of the superclass instead of the method of the current class

         // If you omit super, this method calls itself.

}





◆ Subclass Construction

- To call the superclass constructor, use the super reserved word in the first statement of the subclass constructor ( * super constructor -> super(parameter); )


- When subclass constructor doesn't call superclass constructor, the superclass must have a constructor with no parameters

* If, however, all constructors of the superclass require parameters, then the compiler reports an error


◐ Syntax : Calling a Superclass Constructor

accessSpecifier ClassName ( parameterType prameterName, . . .)

{

    super(parameters);

    .  .  .

}




◆ Converting Between Subclass and Superclass Types

instanceof : Tests whether an object belongs to a particular type 


◐ Syntax : The instanceof Operator

if ( anObject instanceof BankAccount )

// if anObject is null, instanceof returns false

// if anObject can be cast to a BankAccount, return true

{

    BankAccount anAccount = (BankAccount) anObject;

    // The object may belong to a subclas of BankAccount

   

    .  .  .

}




◆ Polymorphism and Inheritance

- Type of a variable does not completely determine type of object to which it refers :

BankAccount aBankAccount = new SavingsAccount(1000);

// aBankAccount holds a reference to a SavingsAccount

BankAccount anAccount = new CheckingAccount();

anAccount.deposit(1000);


Dynamic method lookup : When the virtual machine calls an instance method, it locates the method of the implicit parameter's class

- Polymorphism : Ability to treat objects with differences in behavior in a uniform way




◆ Protected Access

- The designer of the superclass has no control over the authors of subclass:

* Any of the subclass methods can corrupt the superclass data

* Classes with protected instance variables are hard to modify - the protected variables cannot be changed, because someone somewhere out there might have written a subclass whose code depends on them

- Protected data can be accessed by all methods of classes in the same package

- It is best to leave all data private and provide accessor methods for data


(즉, private 변수에 직접 접근하기 보다는 protected method를 거쳐 데이터에 접근하는 것이 좋다는 거!)





◆ Object : The Cosmic Superclass

- All classes defined without an explicit extends clause automatically extend Object 

( Object is the highest Super Class !!! )

- Most useful methods:

> String toString()

> boolean equals(Object otherObject)

> Object clone()

- Good idea to override these methods in your classes


◇ Overriding the toString Method

- Returns a string representation of the object 

- Useful for debugging :

Rectangle box = new Rectangle(5, 10, 20, 30);

  String s = box.toString();

  // Sets s to "java.awt.Rectangle[x=5,y=10,width=20,
// height=30]" 


toString is called whenever you concatenate a string with an object :

"box=" + box;

  // Result: "box=java.awt.Rectangle[x=5,y=10,width=20,
// height=30]" 


Object.toString prints class name and the hash code of the object :

BankAccount momsSavings = new BankAccount(5000);

  String s = momsSavings.toString();

  // Sets s to something like "BankAccount@d24606bf"


 

◇ Overriding the equals Method

- Cannot change parameter : use a cast instead

  public class Coin

  {

     ...

     public boolean equals(Object otherObject)

     {

        Coin other = (Coin) otherObject;

        return name.equals(other.name) && value ==

           other.value;

     }

     ...

  }


- You should also override the hashCode method so that equal objects have the same hash code




◇ Overriding the clone Method

- Copying an object reference gives two references to same object

- Implement clone method to make a new object with the same state as an existing object

- Use clone :

BankAccount clonedAccount =

   (BankAccountaccount.clone();


- Must cast return value because return type is Object


※ The Object.clone Method

   - Create shallow copies

   - Does not systematically clone all subobjects

   - Must be used with caution

   - It is declared as protected ; prevents from accidentally calling x.clone() if the class to which x belongs has not redefined clone to be public

   - You should override the clone method with care




◆ Using Inheritance to Customize Frame

- Use inheritance for complex frames to make programs easier to understand

- Design a subclass of JFrame

- Store the components as instance variable

- Initialize them in the constructor of your subclass

- If initialization code gets complex, simply add some helper methods