COMP 121 Week 3 Inheritance Objectives To learn

COMP 121 Week 3: Inheritance

Objectives To learn about inheritance n To understand how to inherit and override superclass methods n To be able to invoke superclass constructors n To understand the common superclass Object and to override its to. String method n

Introduction to Inheritance n Inheritance ¨ Used with object types that have a certain amount of commonality n n n Mountain bikes, racing bikes, road bikes, and recumbent bikes all share characteristics common to bicycles Squares, triangles, rectangles, and octagons all share characteristics common to polygons Deans, professors, administrators, and technical support personnel all share characteristics common to university employees Surgeons, family doctors, pediatricians, heart specialists all share characteristics common to doctors Savings accounts, checking accounts, money market accounts all share characteristics common to bank accounts

Introduction to Inheritance n Inheritance relationship ¨ Mountain bike inherits from bicycle ¨ Triangle inherits from polygon ¨ Professor inherits from university employee ¨ Pediatrician inherits from doctor ¨ Savings account inherits from bank account n Classes are extended by adding methods and fields ¨ Savings n n account is a bank account with interest Instance field would be added for the interest rate Method would be added to add interest to the account

Inheritance vs. Implementing an Interface n Inheriting from class is not the same as implementing an interface ¨ Subclass n inherits behavior and state Like interfaces, one advantage of inheritance is code reuse Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheritance Diagram n Every class extends the Object class either directly or indirectly Inheritance Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheritance Diagram (Blue. J) Inheritance

UML Diagram (Blue. J) Uses Is-A Inheritance

Inheritance Syntax class Subclass. Name extends Superclass. Name { methods instance fields } The extended class is called the superclass n The extending class is called the subclass n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Question: n If the class Car extends Vehicle, which is the subclass and which is the superclass? Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Subclass versus Superclass Subclass

Inheritance Example public class Savings. Account extends Bank. Account { // Fields and methods unique to a Savings. Account … } n n n Bank. Account is the superclass Savings. Account is the subclass Savings. Account automatically inherits all methods and instance fields of Bank. Account Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Subclass Fields and Methods n In subclass: ¨ Add new instance fields and methods ¨ Change or override methods public class Savings. Account extends Bank. Account { public Savings. Account(double rate) { interest. Rate = rate; } public void add. Interest() { double interest = get. Balance() * interest. Rate / 100; deposit(interest); } private double interest. Rate; } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Subclass Object Savings. Account object inherits the balance instance field from Bank. Account n Additional instance field is interest. Rate n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Encapsulation and Inheritance public void add. Interest() { double interest = get. Balance() * interest. Rate / 100; deposit(interest); } n Encapsulation calls get. Balance rather than updating the balance field of the superclass (field is private) ¨ add. Interest calls get. Balance without specifying the implicit parameter ¨ add. Interest n Call applies to the same object (this) Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheritance Hierarchies n Sets of classes can form complex inheritance hierarchies Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheritance Hierarchies: Swing Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Hierarchy of Bank Accounts n Consider a bank that offers its customers the following account types: Checking account: no interest; small number of free transactions per month, additional transactions are charged a small fee 2. Savings account: earns interest that compounds monthly 1. Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Hierarchy of Bank Accounts Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Hierarchy of Bank Accounts Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Subclass vs. Superclass Methods All bank accounts support the get. Balance method n All bank accounts support the deposit and withdraw methods, but the implementations differ (checking account needs to count transactions) n Checking account needs a method deduct. Fees n Savings account needs a method add. Interest n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Overriding vs. Inheriting Methods n Overriding a method ¨ Supply a different implementation of a method that exists in the superclass ¨ Must have same signature (same name and same parameter types) ¨ If method is called on an object of the subclass type, the overriding method is executed Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Overriding vs. Inheriting Methods n Inheriting a method (behavior) ¨ Don't supply a new implementation of a method that exists in superclass ¨ Superclass method can be called on the subclass objects Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Defining New Methods n Add a method ¨ Supply a new method that doesn't exist in the superclass ¨ New method can be called only on subclass objects Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheriting Instance Fields Can't override fields n All fields from the superclass are automatically inherited n New fields that don't exist in the superclass can be added to the subclass n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheriting Instance Fields n What if you define a new field with the same name as a superclass field? ¨ Each object would have two instance fields of the same name ¨ Fields can hold different values ¨ Legal but extremely undesirable ¨ DON’T DO IT!!! Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Checking. Account Implementation n Overrides deposit and withdraw to increment the transaction count public class Checking. Account extends Bank. Account { public void deposit(double amount) {. . . } public void withdraw(double amount) {. . . } public void deduct. Fees() {. . . } // new method private int transaction. Count; // new instance field } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Checking. Account Implementation n Each Checking. Account object has two instance fields: (inherited from Bank. Account) ¨ transaction. Count (new to Checking. Account) ¨ balance Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Checking. Account Implementation n You can apply four methods to Checking. Account objects: (inherited from Bank. Account) ¨ deposit(double amount) (overrides Bank. Account method) ¨ withdraw(double amount) (overrides Bank. Account method) ¨ deduct. Fees() (new to Checking. Account) ¨ get. Balance() Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Accessing Private Fields in Superclass n Consider deposit method of Checking. Account public void deposit(double amount) { transaction. Count++; // now add amount to balance . . . } n n Can't just add amount to balance is a private field of the superclass Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Accessing Private Fields in Superclass A subclass has no access to private fields of its superclass n Subclass must use public interface n So how can we add the amount to the balance? Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Invoking a Super Class Method n Can't just call deposit(amount)in deposit method of Checking. Account n That is the same as this. deposit(amount) Calls the same method (infinite loop) n Instead, invoke superclass method super. deposit(amount) n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Invoking a Superclass Method public void deposit(double amount) { // Increment the transaction count transaction. Count++; // Now add amount to balance super. deposit(amount); } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Subclass Construction n n The super keyword is also used to call a constructor super followed by parameters in parentheses indicates a call to the superclass constructor Must be the first statement in subclass constructor If subclass constructor doesn't explicitly call superclass constructor, the default superclass constructor is used ¨ Default constructor -- constructor with no parameters ¨ If all superclass constructors require parameters, it’s a compile error Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Subclass Construction public class Checking. Account extends Bank. Account { public Checking. Account(double initial. Balance) { // Construct superclass super(initial. Balance); // Initialize transaction count transaction. Count = 0; } . . . } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Converting Between Subclass and Superclass Types n Can convert a subclass reference to superclass reference Savings. Account college. Fund = new Savings. Account(10); Bank. Account an. Account = college. Fund; Object an. Object = college. Fund; n The three object references stored in college. Fund, an. Account, and an. Object all refer to the same object of type Savings. Account Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Converting Between Subclass and Superclass Types Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Converting Between Subclass and Superclass Types n Superclass references don't know about methods in the subclass an. Account. deposit(1000); // OK an. Account. add. Interest(); // Not OK n When you convert a subclass object to its superclass type ¨ The value of the reference stays the same (actual memory location of the object) ¨ Less information is known about the object Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Converting Between Subclass and Superclass Types n Why would anyone want to know less about an object? ¨ Reuse code that knows about the superclass public void transfer(double amount, Bank. Account other) but not the subclass: { withdraw(amount); other. deposit(amount); } n Can be used to transfer money from any type of Bank. Account Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Converting Between Subclass and Superclass Types n Occasionally you need to convert from a superclass reference to a subclass reference Bank. Account an. Account = (Bank. Account) an. Object; n If object types are unrelated (not a superclass/ subclass relationship), an exception is thrown at runtime Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

instanceof operator n n n Tests whether an object belongs to a particular type Returns true if the object on the left hand side of the operator is an instance of the type on the right hand side of the operator Otherwise, returns false if (an. Object instanceof Bank. Account) { Bank. Account an. Account = (Bank. Account) an. Object; . . . } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Object: The Cosmic Superclass n All classes defined without an explicit extends clause automatically extend Object Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Useful Methods in the Object Class n n String to. String() boolean equals(Object other. Object) Object clone() Good idea to override these methods in your classes ¨ Will not be overriding clone() in this course Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Overriding the to. String Method Returns a string representation of the object n Useful for debugging n Rectangle box = new Rectangle(5, 10, 20, 30); String s = box. to. String(); // Sets s to "java. awt. Rectangle[x=5, y=10, width=20, height=30]" Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Overriding the to. String Method n to. String 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]" n Object. to. String default behavior is to print the class name and the hash code of the object Bank. Account moms. Savings = new Bank. Account(5000); String s = moms. Savings. to. String(); // Sets s to something like "Bank. Account@d 24606 bf" Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Overriding the to. String Method n In Bank. Account: public String to. String() { return "Bank. Account[balance=" + balance + "]"; } n Converts Bank. Account object to a String Bank. Account moms. Savings = new Bank. Account(5000); String s = moms. Savings. to. String(); // Sets s to "Bank. Account[balance=5000]" n Used by System. out. println Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheritance and to. String Method n n n to. String method often returns the class name and the names and values of the instance fields in a class In a superclass, to be usable by subclasses, get the class name instead of hard-coding it For example, in Bank. Account: public String to. String() { return get. Class(). get. Name()+" [balance =" + balance + "]"; } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Inheritance and to. String Method n n In a subclass, first get the string that represents the superclass, then add the subclass information For example, in Savings. Account: public String to. String() { return super. to. String() + " [interest. Rate = " + interest. Rate + "]"; } Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Summary Inheritance is used to extend existing classes by adding methods and fields n The more general class is called the superclass n The more specialized class that inherits from the superclass is called the subclass n The subclass inherits both state and behavior from the superclass n Code reuse is one advantage of inheritance n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Summary (continued) Methods in the superclass can be changed or overridden in the subclass n A subclass cannot access the private fields of the superclass n The super keyword is used to call a method of the superclass n The super keyword may also be used as the first statement of the subclass constructor to call the superclass constructor n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Summary (continued) The instanceof operator tests whether an object belongs to a particular type n The to. String method should be overridden to return a String that represents the object’s state n Horstmann, C. (2008). Big Java (3 rd ed. ). New York: John Wiley & Sons.

Any Questions?
- Slides: 52