120 likes | 132 Views
Learn how to extend existing classes in Java by adding or redefining methods and instance fields, with examples on inheritance, overriding methods, and implementing constructors.
E N D
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 CheckingAccountpublic 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 • Interface is not a class • 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: • String toString() • boolean equals(Object otherObject) • Object clone()
Overriding the toString Method • Returns a string representation of the object • Useful for debugging • Example: Rectangle.toString returns something likejava.awt.Rectangle[x=5,y=10,width=20,height=30] • toString used by concatenation operator • aString + anObjectmeans aString + anObject.toString() • Object.toString prints class name and object addressBankAccount@d2460bf • Override toString:public class BankAccount{ public String toString() { return "BankAccount[balance=" + balance + "]"; } . . .}
Overriding the equals Method • equalstests 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; }}
Overriding the clone Method • Copying object reference gives two references to same objectBankAccount 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