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 CheckingAccount public void deposit(double amount) { transactionCount++; // 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, getBalance on SavingsAccount object Extended class = superclass, extending class = subclass Inheritance is different from realizing an interface oInterface is not a class oInterface 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 toString() o boolean equals(Object otherObject) o Object clone()
The Object Class is the Superclass of Every Java Class
Overriding the toString Method Returns a string representation of the object Useful for debugging Example: Rectangle.toString returns something like java.awt.Rectangle[x=5,y=10,width=20,height=30] toString used by concatenation operator aString + anObject means aString + anObject. toString() Object.toString prints class name and object address Override toString : public class BankAccount { public String toString() { return "BankAccount[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 otherObject) { Coin other = (Coin)otherObject; 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 BankAccount account2 = account1 ; Sometimes, need to make a copy of the object Use clone: BankAccount account2 = (BankAccount)account1. clone () ; Must cast return value because return type is Object Define clone method to make new object: public Object clone() { BankAccount cloned = new BankAccount(); cloned.balance = balance; return cloned; } Warning: This approach doesn't work with inheritance--see Advanced Topic 11.6