Inheritance INHERITANCE extend existing classes by adding or
Inheritance • INHERITANCE: extend existing classes by adding or redefining methods, and adding instance fields Suppose we have a class Vehicle: public class Vehicle{ String type; String model; }
• We want a class which to represent a Car. This class will need all of the attributes of a standard Vehicle plus some more. .
Inherited Fields are Private • Consider deposit method of Checking. Account public void deposit(double amount) { transaction. Count++; // now add amount to balance . . . } • Can't just add amount to balance • balance is a private field of the superclass • Subclass must use public interface
• • and all data of Vehicle are automaticaly inherited by class Car Ok to call deposit, get. Balance on Savings. Account object Extended class = superclass, extending class = subclass Inheritance is different from realizing an interface o Interface is not a class o Interface supplies no instance fields or methods to inherit
• We want a class which to represent Cars. This class will need all of the behavior of a standard Vehicle plus some more. . • Constructor (calling superclass constructor
Object: The Cosmic Superclass • All classes extend Object • Most useful methods: o String to. String() o boolean equals(Object other. Object) o Object clone()
The Object Class is the Superclass of Every Java Class
Overriding the to. String Method • • • Returns a string representation of the object Useful for debugging Example: Rectangle. to. String returns something like java. awt. Rectangle[x=5, y=10, width=20, height=30] • to. String used by concatenation operator • a. String + an. Object means a. String + an. Object. to. String() • Object. to. String prints class name and object address Bank. Account@d 2460 bf • Override to. String: public class Bank. Account { public String to. String() { return "Bank. Account[balance=" + balance + "]"; } . . . }
Overriding the equals Method • • equals tests for equal contents == tests for equal location Must cast the Object parameter to subclass public class Coin { public boolean equals(Object other. Object) { Coin other = (Coin)other. Object; return name. equals(other. name) && value == other. value; } }
Two References to Equal Objects
Two References to Same Object
Overriding the clone Method • Copying object reference gives two references to same object Bank. Account account 2 = account 1; • Sometimes, need to make a copy of the object • Use clone: Bank. Account account 2 = (Bank. Account)account 1. clone(); • Must cast return value because return type is Object • Define clone method to make new object: public Object clone() { Bank. Account cloned = new Bank. Account(); cloned. balance = balance; return cloned; } • Warning: This approach doesn't work with inheritance--see Advanced Topic 11. 6
- Slides: 12