object oriented programming: inheritance chapter 9
TRANSCRIPT
Object Oriented Object Oriented Programming: InheritanceProgramming: Inheritance
Chapter 9Chapter 9
22
What You Will LearnWhat You Will Learn
Software reusabilitySoftware reusability(Recycling)(Recycling)
Inheriting data members and methods from Inheriting data members and methods from previously defined classespreviously defined classes
33
IntroductionIntroduction
Software ReusabilitySoftware Reusability saves time in program developmentsaves time in program development encourages use of proven, debugged codeencourages use of proven, debugged code reduces problemsreduces problems
Write programs in general fashionWrite programs in general fashion Enables software designers to deal with Enables software designers to deal with
complexity of modern softwarecomplexity of modern software
44
IntroductionIntroduction
When creating a new class …When creating a new class … designate that class to inherit data members, designate that class to inherit data members,
functions of previously defined functions of previously defined superclasssuperclass result is a result is a subclasssubclass
Subclass adds new data members and Subclass adds new data members and functionsfunctions
Replace and refine existing membersReplace and refine existing members
55
Base Classes & Derived Base Classes & Derived ClassesClasses
Superclass is more generalSuperclass is more general student, shape, loanstudent, shape, loan
Subclass is more specificSubclass is more specific grad student, undergradgrad student, undergrad circle, triangle, rectanglecircle, triangle, rectangle carloan, home improvement, mortgagecarloan, home improvement, mortgage
Some languages talk ofSome languages talk of Base class (Superclass)Base class (Superclass) Derived class (Subclass)Derived class (Subclass)
66
Superclass and SubclassSuperclass and Subclass
Inheritance produces tree like structuresInheritance produces tree like structures
77
Superclass and SubclassSuperclass and Subclass
Inheritance produces tree like structuresInheritance produces tree like structures
88
Design TipDesign Tip
Important link between subclass and Important link between subclass and superclasssuperclass The “IS-A” relationshipThe “IS-A” relationship
ExamplesExamples A checking account IS-A banking accountA checking account IS-A banking account A savings account IS NOT a checking accountA savings account IS NOT a checking account
If there is no IS-A relationship, do not If there is no IS-A relationship, do not use inheritanceuse inheritance
Sun comments on the concept of inheritance
Sun comments on the concept of inheritance
99
protectedprotected Members Members
protectedprotected access access Intermediate level of protection between Intermediate level of protection between publicpublic
and and privateprivate protectedprotected members accessible by members accessible by
superclass memberssuperclass members subclass memberssubclass members Class members in the same packageClass members in the same package
Subclass access to superclass memberSubclass access to superclass member Keyword Keyword supersuper and a dot (.) and a dot (.)
1010
Comments on Private vs. ProtectedComments on Private vs. Protected
Use Use protectedprotected when when Superclass should provide a service only to its Superclass should provide a service only to its
subclassessubclasses Should not provide service to other clientsShould not provide service to other clients
Use Use privateprivate so that so that Superclass implementation can change without affecting Superclass implementation can change without affecting
subclass implementationssubclass implementations
Author advocates avoiding Author advocates avoiding protectedprotected Instead provide set and get methods to access Instead provide set and get methods to access privateprivate
data items (see data items (see Figures 9.12Figures 9.12, , 9.139.13 in text) in text)
1111
Relationship between Superclasses Relationship between Superclasses and Subclassesand Subclasses
Superclass and subclass relationshipSuperclass and subclass relationship Example: Example: CommissionEmployee/CommissionEmployee/BasePlusCommissionEmployeeBasePlusCommissionEmployee inheritance inheritance hierarchyhierarchy CommissionEmployeeCommissionEmployee
First name, last name, SSN, commission rate, gross sale First name, last name, SSN, commission rate, gross sale amountamount
BasePlusCommissionEmployeeBasePlusCommissionEmployee First name, last name, SSN, commission rate, gross sale First name, last name, SSN, commission rate, gross sale
amountamount Base salaryBase salary
1212
Creating and Using a Creating and Using a CommissionEmployeeCommissionEmployee Class Class
Class Class CommissionEmployeeCommissionEmployee Extends class Extends class ObjectObject
Keyword Keyword extendsextends Every class in Java extends an existing classEvery class in Java extends an existing class
Except Except ObjectObject
Every class inherits Every class inherits ObjectObject’s methods’s methods New class implicitly extends ObjectNew class implicitly extends Object
If it does not extend another classIf it does not extend another class
1313
Creating and Using a Creating and Using a CommissionEmployeeCommissionEmployee Class Class
Class Class CommissionEmployeeCommissionEmployee Extends class Extends class ObjectObject
Keyword Keyword extendsextends Every class in Java extends an existing classEvery class in Java extends an existing class
Except Except ObjectObject
Every class inherits Every class inherits ObjectObject’s methods’s methods New class implicitly extends ObjectNew class implicitly extends Object
If it does not extend another classIf it does not extend another class
View class View class Figure 9.4Figure 9.4View test program, View test program, Figure 9.5Figure 9.5
1414
Creating a Creating a BasePlusCommissionEmployeeBasePlusCommissionEmployee
Class Class withoutwithout Using Inheritance Using InheritanceClass Class BasePlusCommissionEmployeeBasePlusCommissionEmployee
Implicitly extends Implicitly extends ObjectObject Much of the code is similar to Much of the code is similar to CommissionEmployeeCommissionEmployee privateprivate instance variables instance variables publicpublic methods methods constructorconstructor
AdditionsAdditions privateprivate instance variable instance variable baseSalarybaseSalary Methods Methods setBaseSalarysetBaseSalary and and getBaseSalarygetBaseSalary
View classFigure 9.6View classFigure 9.6
View test program
Figure 9.7
View test program
Figure 9.7
1515
Creating a Creating a CommissionEmployee-CommissionEmployee-BasePlusCommiionEmployeeBasePlusCommiionEmployee Inheritance Inheritance
HierarchyHierarchy
Class Class BasePlusCommissionEmployee2BasePlusCommissionEmployee2 Extends class Extends class CommissionEmployeeCommissionEmployee Is a Is a CommissionEmployeeCommissionEmployee Has instance variable Has instance variable baseSalarybaseSalary Inherits Inherits publicpublic and and protectedprotected members members Constructor not inheritedConstructor not inherited
Note these points plus Note these points plus invalidinvalid references, references, Figure 9.8 Figure 9.8 – note compiler – note compiler error messageserror messages
1616
Using Using protectedprotected Instance Variables Instance Variables
Use Use protectedprotected instance variables instance variables Enable class Enable class BasePlusCommissionEmployeeBasePlusCommissionEmployee
to directly access superclass instance variablesto directly access superclass instance variables Superclass’s Superclass’s protectedprotected members are inherited members are inherited
by all subclases of that superclassby all subclases of that superclass
View version that now works, View version that now works, Figure 9.10Figure 9.10Test program, Test program, Figure 9.11Figure 9.11
1717
Using Using protectedprotected Instance Variables Instance VariablesAdvantagesAdvantages
SubclassesSubclasses can modify values directlycan modify values directlySlight increase in performanceSlight increase in performance
Avoid set/get methodAvoid set/get method call overhead call overhead
1818
Using Using protectedprotected Instance Variables Instance VariablesDisadvantagesDisadvantages
No validity checkingNo validity checking subclass can assign illegal valuesubclass can assign illegal value
Implementation dependentImplementation dependent subclass methods more likely dependent on subclass methods more likely dependent on
superclass implementationsuperclass implementation superclass implementation changes may result superclass implementation changes may result
in subclass modificationsin subclass modifications Fragile (brittle) softwareFragile (brittle) software
1919
Reexamine HierarchyReexamine Hierarchy
Use the best software engineering practiceUse the best software engineering practice Declare instance variables as Declare instance variables as privateprivate Provide public Provide public getget and and setset methods methods Use Use getget method to obtain values of instance method to obtain values of instance
variablesvariablesView new version of CommissionEmployee, View new version of CommissionEmployee,
Figure 9.12Figure 9.12New version of New version of
BasePlusCommissiionEmployee, Figure 9.13BasePlusCommissiionEmployee, Figure 9.13Test program, Figure 9.14Test program, Figure 9.14
2020
Instantiating Subclass ObjectInstantiating Subclass ObjectChain Of Constructor CallsChain Of Constructor Calls
Subclass constructor invokes superclass Subclass constructor invokes superclass constructorconstructor Implicitly or explicitlyImplicitly or explicitly
Base of inheritance hierarchyBase of inheritance hierarchy Last constructor called in chain is Last constructor called in chain is ObjectObject’s constructor’s constructor Original subclass constructor’s body finishes executing Original subclass constructor’s body finishes executing
lastlast
2121
Instantiating Subclass ObjectInstantiating Subclass ObjectChain Of Constructor CallsChain Of Constructor Calls
Example, Figure 9.15 : Example, Figure 9.15 : CommissionEmployee3-CommissionEmployee3-BasePlusCommissionEmployee4BasePlusCommissionEmployee4 hierarchy hierarchy CommissionEmployee3CommissionEmployee3 constructor called second last constructor called second last
(last is (last is Object Object constructor)constructor) CommissionEmployee3CommissionEmployee3 constructor’s body finishes constructor’s body finishes
execution second (first is execution second (first is ObjectObject constructor’s body) constructor’s body)
Figure 9.16, BasePlusCommissionEmploye5Figure 9.16, BasePlusCommissionEmploye5Figure 9.17, Test program, demonstrates Figure 9.17, Test program, demonstrates
constructor callsconstructor calls
2222
Software Engineering with Software Engineering with InheritanceInheritance
At the design stage, certain classes found to At the design stage, certain classes found to be closely relatedbe closely related Factor out common attributes, behaviorsFactor out common attributes, behaviors Place these in a superclassPlace these in a superclass Use inheritance to develop subclasses with Use inheritance to develop subclasses with
inherited capabilitiesinherited capabilities This avoids proliferation of classes, This avoids proliferation of classes,
"reinventing the wheel""reinventing the wheel" NoteNote
Declaring a subclass does not affect superclass Declaring a subclass does not affect superclass source codesource code