DOC PREVIEW
UMD CMSC 131 - Lecture Set #19: Inheritance

This preview shows page 1-2-3-4 out of 12 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 12 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1CMSC 131 Sping 2008Jan Plane (adapted from Bonnie Dorr)Lecture Set #19:InheritanceInheritanceConceptualIs-A relationship compared to contains-aTerminologyOverloading compared to OverridingsuperisInstanceOf and getClass()CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)1InheritanceA crucial feature of object-oriented programming languagesOne class (derived class, subclass) is constructed …… by including (extending, inheriting) information …… from another (base class, superclass, parent class) …… and adding new information / redefining existingExampleBase class: ClocksetTimegetTimetickDerived class: Alarm ClockSame 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” ClockOperations on Clock (e.g. setTime) should be inherited by Alarm ClockAlarm Clock should only have to add information specific to alarm clockssetAlarmringInheritance provides just this capability2CMSC 131 Spring 2008Jan Plane (adapted from Bonnie Dorr)3InheritanceOne 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 informationTo 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 ShapeDerived class: public class Circle extends ShapeDerived class inherits all instance variables, methods from base class. It can also define new instance variables, methodsPolymorphism: 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 GenerallyClasses / objects have a natural “is-a” hierarchyObject-oriented programming provides mechanisms for exploiting this forCode re-useCommon operations implemented in super classesPolymorphismObjects 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 UniversityBase class: personDerived classes: student, faculty, administratorDerived 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 OrderWhen you create a new derived class object:Java allocates space for base class instance variables and derived class variablesJava initializes base class variables first, and then the derived class variablesExamplePerson 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 OverridingA 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. OverloadingOverriding: a derived class defines a method with same name, parameters as base class Overloading: two or more methods have the same name, but different parametersExamplepublic 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 functionPossible 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

UMD CMSC 131 - Lecture Set #19: Inheritance

Documents in this Course
Set #3

Set #3

7 pages

Exam #1

Exam #1

6 pages

Exam #1

Exam #1

6 pages

Notes

Notes

124 pages

Notes

Notes

124 pages

Load more
Download Lecture Set #19: Inheritance
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Set #19: Inheritance and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Set #19: Inheritance 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?