1CMSC 131 Sping 2008Jan Plane (adapted from Bonnie Dorr)Lecture Set #19:InheritanceInheritanceConceptualIs-A relationship compared to contains-aTerminologyOverloading compared to OverridingsuperisInstanceOf and getClass()CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)1InheritanceA crucial feature of object-oriented programming languagesOne class (derived class, subclass) is constructed …… by including (extending, inheriting) information …… from another (base class, superclass, parent class) …… and adding new information / redefining existingExampleBase class: ClocksetTimegetTimetickDerived class: Alarm ClockSame methods as Clock plus a few additional ones: setAlarm, ringCMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)2Can We Avoid Code Copying and therefore redundancy?Alarm Clock “IS-A” ClockOperations on Clock (e.g. setTime) should be inherited by Alarm ClockAlarm Clock should only have to add information specific to alarm clockssetAlarmringInheritance provides just this capability2CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)3InheritanceOne class (derived class, subclass, child class) is constructed by including (extending, inheriting) information from another (base class, superclass, parent class) then also adding new information and/or redefining existing informationTo derive a class D from a base class B, use:public class D extends B { … }Example (we will look at this in next two slides):Base class: public class ShapeDerived class: public class Circle extends ShapeDerived class inherits all instance variables, methods from base class. It can also define new instance variables, methodsPolymorphism: object in derived class can be used anywhere base class is expected (an alarmClock “is a” Clock!)CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)4Inheritance More GenerallyClasses / objects have a natural “is-a” hierarchyObject-oriented programming provides mechanisms for exploiting this forCode re-useCommon operations implemented in super classesPolymorphismObjects in subclasses can be used wherever superclass objects are neededShapeCircle RectangleTriangleRight-Triangle Equilateral-TriangleAnimalInsect ReptileMammalCat DogPrimateHuman Ape HomerCMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)5Example: People at UniversityBase class: personDerived classes: student, faculty, administratorDerived from those: undergrad, grad, instructor, professor,…PersonStudent Faculty AdministratorUndergrad GradStudent Instructor Professor……PersonStudent Faculty3CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)6University Person Exampleclass: Personinstance variables:String nameString idNummethods:Person( … ) [various]String getName( )String getIdNum( )void setName( String )void setIdNum( String )String toString( )boolean equals( Person )class: Studentinstance variables:int admitYeardouble gpamethods:Student( … ) [various]int getAdmitYear( )double getGpa( )void setAdmitYear( int )void setGpa( double )String toString( )boolean equals( Student )extends Personclass: Facultyinstance variables:int hireYearmethods:Faculty( … ) [various]int hireYear( )void setHireYear( int )String toString( )boolean equals( Faculty )extends PersonCMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)7HeapMemory Layout and Initialization OrderWhen you create a new derived class object:Java allocates space for base class instance variables and derived class variablesJava initializes base class variables first, and then the derived class variablesExamplePerson ted = new Person("Ted Goodman", "111-22-3333" );Student carole = new Student(“Carole Goode", "123-45-6789", 2004, 4.0 );tedcaroleTed Goodman111-22-3333Carole Good123-45-6789super( n, id )builds thePerson part20044.0Student constructor finishes it offCMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)8Method OverridingA derived class can define new instance variables and methods (e.g. hireYear and getHireYear( ) )A derived class can also redefine (override) existing methodspublic class Person {…public String toString( ) { … }}public class Student extends Person {…public String toString( ) { … }}Student bob =new Student("Bob Goodstudent","123-45-6789",2004,4.0 );System.out.println( "Bob's info: " + bob.toString( ) );Overrides base-classdefinition of this methodSince bob is Student,Student toString used4CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)9Overriding vs. OverloadingOverriding: a derived class defines a method with same name, parameters as base class Overloading: two or more methods have the same name, but different parametersExamplepublic class Person {public void setName( String n ) { name = n; }…}public class Faculty extends Person {public void setName( String n ) { super.setName( “The Evil Professor ” + n ); }public void setName( String first, String last ) {super.setName( first + “ ” + last );}}Base class setName( )OverridingOverloadingCMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)10Calling an overridden functionPossible but use sparingly.Overriding hides methods of the base class (can still access them using super.methodName() in subclass, but not in “outside world”)public class Person {public String toString(){ /*one def here*/}…}public class Administrator extends Person {public String toString(){/*different def here*/}public String regPrint(){return super.toString(); /* will use Person’s def of toString*//*return toString(); will use Administrator’s def of toString*/}}Often better to pick a different name rather than overload if you want both.CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)11Derived class: Studentpackage university;public class Student extends Person {private int admitYear;private double gpa;public Student( ) {super( );admitYear = -1;gpa = 0.0;}public Student( String n, String id, int yr, double g ) {super( n, id );admitYear = yr;gpa = g;}public Student( Student s ) {super( s );admitYear = s.admitYear;gpa = s.gpa;}// …other methods in part 2}Additional instance variablesDefault constructorStandard constructorCopy constructorThis calls the default constructorfor base class (superclass),Person, to set name and idNum.Calls Person constructor.Calls Person copy constructor.Tells Java that Student is derived from Person5CMSC 131
View Full Document