inheritance type/subtype relationship. inheritance idea: an object b of one type, termed child...
DESCRIPTION
The Class Object Extends any class, by definition Extends any class, by definition Has the general methods Has the general methods equals()-- meaning this and its parameter have the same content equals()-- meaning this and its parameter have the same content getClass()-- returns the class of the object that invokes it, e.g. getClass()-- returns the class of the object that invokes it, e.g. if (X.getClass()==IdTree.class)... if (X.getClass()==IdTree.class)... hashCode()-- computes the hash value of a key hashCode()-- computes the hash value of a key toString()-- converts the class to a string toString()-- converts the class to a stringTRANSCRIPT
InheritanceInheritanceType/Subtype RelationshipType/Subtype Relationship
InheritanceInheritance
• IdeaIdea: An object: An object B B of one type, termed child class, of one type, termed child class, inheritsinherits from another object from another object A A of another type, of another type, termed parent class, if termed parent class, if BB can access the data and can access the data and methods ofmethods of A A
• Loosely speaking, we can also say that the child Loosely speaking, we can also say that the child class class inheritsinherits from the parent class from the parent class
• In Java every class inherits from the In Java every class inherits from the ObjectObject class, i.e. class, i.e. Object Object is parent to every classis parent to every class
The Class The Class ObjectObject
• Extends any class, by definitionExtends any class, by definition• Has the general methodsHas the general methods
• equals()--equals()--meaning this and its parameter meaning this and its parameter have the same contenthave the same content
• getClass()--getClass()--returns the class of the object returns the class of the object that invokes it, e.g.that invokes it, e.g.
• if (X.getClass()==IdTree.class)if (X.getClass()==IdTree.class) ... ...• hashCode()--hashCode()--computes the hash value of a computes the hash value of a
keykey• toString()--toString()--converts the class to a stringconverts the class to a string
InterfacesInterfaces• Inheritance is also employed hereInheritance is also employed here• But interfaces inherit specificationBut interfaces inherit specification• Classes inherit code (and data)Classes inherit code (and data)• Thus classes derived from some abstract class will Thus classes derived from some abstract class will
share an interface (share an interface (proper inheritanceproper inheritance))• Inheritance of interfaces sometimes called Inheritance of interfaces sometimes called
subtypingsubtyping• An object’s An object’s classclass indicates how the object is indicates how the object is
implementedimplemented• An object’s An object’s typetype refers to its interface refers to its interface
Inheritance: Class vs InterfaceInheritance: Class vs Interface• ClassClass: An object’s implementation is given in : An object’s implementation is given in
terms of another’s implementationterms of another’s implementation• InterfaceInterface (subtyping): One object can be used in (subtyping): One object can be used in
place of anotherplace of another• C++ and Java use both types of inheritanceC++ and Java use both types of inheritance• Smalltalk uses only class inheritanceSmalltalk uses only class inheritance
• No subtyping, because variable types are not declaredNo subtyping, because variable types are not declared• Instances of any class can be assigned to a variable as Instances of any class can be assigned to a variable as
long as those instances support the operations long as those instances support the operations performed on the variable’s operationsperformed on the variable’s operations
Subclass, Subtype & Subclass, Subtype & SubstitutabilitySubstitutability
• SubclassSubclass: Refers to the : Refers to the wayway of deriving, or of deriving, or inheriting, one class from another, i.e. in inheriting, one class from another, i.e. in Java by the keyword Java by the keyword extendsextends
• There are various heuristics to subclassingThere are various heuristics to subclassing• These are not recognizable from the These are not recognizable from the
program source, but rather from the program source, but rather from the kindkind of of subclassing being implementedsubclassing being implemented
Subclassing TaxonomySubclassing Taxonomy
• SpecializationSpecialization: the : the is_ais_a relation. This is relation. This is also the subtype relation, e.g. Physics also the subtype relation, e.g. Physics is_ais_a Science, Putin Science, Putin is_ais_a Russian Russian• CompositionComposition: the : the has_ahas_a relation. E.g. a human relation. E.g. a human
has_a (n) arm.has_a (n) arm.• SpecificationSpecification: Parent has abstract methods : Parent has abstract methods
that specify the behavior of the subclassthat specify the behavior of the subclass• public MyGUI extends JFramepublic MyGUI extends JFrame• Most ideal type of inheritanceMost ideal type of inheritance
Sublassing TaxonomySublassing Taxonomy
• ConstructionConstruction:Just a trick, because there is :Just a trick, because there is no real relation between the class and its no real relation between the class and its subclass (use the parent’s behavior)subclass (use the parent’s behavior)• Use a Vector to implement a Stack:Use a Vector to implement a Stack:
class Stack extends Vector{
public void push(Object item)
addelement(item);}
public boolean empty(){return isEmpty():}
Subclassing TaxonomySubclassing Taxonomy
• GeneralizationGeneralization: generalize the behavior of : generalize the behavior of the parent (the opposite of specialization).the parent (the opposite of specialization).• If you implement a background color If you implement a background color
Black&White and use this to define a Black&White and use this to define a BWWindowBWWindow class, you class, you generalizegeneralize if you derive a if you derive a ColorWindowColorWindow from it. from it.
• Better: subclass the other way roundBetter: subclass the other way round
Subclassing TaxonomySubclassing Taxonomy
• Extension:Extension: Add completely new behavior in Add completely new behavior in the child. Add new functionality not in the the child. Add new functionality not in the parentparent• E.g. E.g. public class Properties extends public class Properties extends HashtableHashtable
• Use the parent Use the parent HashtableHashtable to store and to store and retrieve, but also define a new method, e.g.:retrieve, but also define a new method, e.g.:
public synchronized void load(InputStream in) throws IOException;
Subclassing TaxonomySubclassing Taxonomy
• LimitationLimitation: If you do not have access to the : If you do not have access to the parent, override the irrelevant methods, i.e. parent, override the irrelevant methods, i.e. the subclass is a restriction of the parent the subclass is a restriction of the parent classclass• Of questionable valueOf questionable value• E.g. if you wanted to use E.g. if you wanted to use VectorVector to implement to implement
a a SetSet, override the , override the elementAt(int index)elementAt(int index) method, since it is irrelevant method, since it is irrelevant
• Can’t do this in this case anyway (method is Can’t do this in this case anyway (method is finalfinal))
Subclass, Subtype and Subclass, Subtype and SubstitutabilitySubstitutability
• SubstitutabilitySubstitutability:When can one type be used in :When can one type be used in place of another? What does this mean?place of another? What does this mean?
• E.g. in Pascal:E.g. in Pascal:
• Can Can ComplexComplex and and VectorVector be used be used interchangeably in a program?interchangeably in a program?
• In Pascal these are distinct type: type equivalent, In Pascal these are distinct type: type equivalent, but not type identicalbut not type identical
type Cpmplex = record x:real; y:real end;
type Vector = record x:real; y:real end;
Liskov Substitutability PrincipleLiskov Substitutability Principle
• PrinciplePrinciple (Liskov): If for each object (Liskov): If for each object OO11 of of type type SS there is an object there is an object OO22 of type of type TT such such that for all programs that for all programs PP defined in terms of defined in terms of TT the behavior of the behavior of PP is unchanged where is unchanged where OO11 is is substituted for substituted for OO22 then then SS is a is a subtypesubtype of of TT, , or or SS can be can be substitutedsubstituted for for TT
• This means: if you use This means: if you use OO11 instead of instead of OO22 in in PP there is no observable changethere is no observable change from running from running PP with with O2O2
Budd’s VersionBudd’s Version
1.1. Instances of the subclass must possess all data Instances of the subclass must possess all data fields associated with the parent classfields associated with the parent class
2.2. Instances of the subclass must implement, Instances of the subclass must implement, through inheritance at least, all functionality through inheritance at least, all functionality defined forthe parent classdefined forthe parent class
3.3. Thus, an instance of a child class can mimic the Thus, an instance of a child class can mimic the behavior of the parent class and should be behavior of the parent class and should be indistinguishableindistinguishable from an instance of the parent from an instance of the parent class if substituted in a similar situationclass if substituted in a similar situation
RemarksRemarks
• This is a test for determining substitutabilityThis is a test for determining substitutability• Note the removal of the overridden clauseNote the removal of the overridden clause• Note the Note the no observable behaviorno observable behavior!!!!
ExampleExample
• Write some Java code to implement a Write some Java code to implement a typical bank account as given by the class typical bank account as given by the class CurrentAccount. Nothing special here.CurrentAccount. Nothing special here.
• Now define another account Now define another account SpecialCurrentAccount by extending SpecialCurrentAccount by extending CurrentAccount that pays more interest, but CurrentAccount that pays more interest, but requires that the account be opened for requires that the account be opened for longer than the default periodlonger than the default period
CurrentAccountCurrentAccountpublic class CurrentAccount{protected int balance;protected int period;public CurrentAccount(int balance, int period){ this.balance = balance; this.period = period;}
public boolean openAccount(int balance){ this.balance = balance;}
public boolean closeAccount{ if (balance > 0) return true; else return false;}
public int getBalance(){return this.balance;}
public void setBalance(int balance){ this.balance = balance:}
public int getPeriod(){return this.period;}
public void setPeriod(int period){
this.period = period;
}
}
SpecialCurrentAccountSpecialCurrentAccountpublic class SpecialCurrentccount extends CurrentAccount{ private int defaultPeriod = 6;
public SpecialCurrentAccount(int balance, int period}{ super(balance, period);}
public boolean closeAccount(){ if (balance>0 && period>defaultPeriod) return true; else return false;}
public int getDefaultPeriod(){ return this.defaultPeriod:}
public void seDefaultPeriod(int defaultPeriod){ this.defaultPeriod = defaultPeriod;}
AccountTestAccountTestpublic class AccountTest{
public void closeAnAccount(CurrentAccount ac){ System.out.println(“Account close result: ac.closeAccount()): }}
Now Close 2 AccountsNow Close 2 Accounts
• One is to be normal and the other special:One is to be normal and the other special:
public static void main(String[] args){ AccountTest test =new AccountTest(); CurrentAccount ac = new CurrentAccount(100,2); SpecialCurrentAccount sac = new SpecialCurrentAccount (200,5); test.closeAnAccount(ac); test.closeAnAccount(sac);}
ResultResult• Liskov Substitution Principle is violated!Liskov Substitution Principle is violated!• If the bank customer uses a If the bank customer uses a SpecialCurrentAccount SpecialCurrentAccount where a where a CurrentAccountCurrentAccount is expected, the customer is in is expected, the customer is in for a surprisefor a surprise
• Big problem: the outcome is only predictable by Big problem: the outcome is only predictable by examining the codeexamining the code
• Way out: use an abstract base class:Way out: use an abstract base class:
Account
+closeAccount:bool
+closeAccount:bool +closeAccount:bool
CurrentAccount SpecialCurrentAccount