Superclasses Subclasses Inheritance Allows for more usability of code Page 168 of Heads First book Class SuperHero Classes Suits tights specialPower Methods useSpecialPower ID: 414253
Download Presentation The PPT/PDF document "Inheritance," is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Inheritance, Superclasses, SubclassesSlide2
Inheritance
Allows for more usability of code
Page 168 of Heads First book
Class –
SuperHero
(Classes) Suits; tights;
specialPower
(Methods)
useSpecialPower
;
putOnSuit
Think of Parent/Child Relationship
The sub-class Inherits from the
SuperClass
In Java, we say the
subclass
extends the
SuperClass
.Slide3
Overriding Methods
You have the ability to override the method that are received from the parent.
What you override is then specific to that subclass.
SuperClass
– class that is inherited from – more abstract
Subclass – the specific “children” of the
superclass
.Slide4
Page 169 Example -
Doctor –
superclass
Subclasses – Family Doctor, Surgeon
Any subclass of Doctor will have a
WorksAtHospital
& a
treatPatient
property
Extends – means “inherits from”
CODE
Public class
FamilyDoctor
extends Doctor
{
Can then put items specific to that class Slide5
Surgeon – page 169
Look at surgeon class
TreatPatient
method overrides the
TreatPatient
method in doctor class.
A surgeon treats a patient by performing surgery, so that method overrides the method in Doctor class.
Surgeon also has a
MakeIncision
methodSlide6
Page 170 – Inheritance Tree Design
Look for objects that have common attributes and behaviors
Use inheritance to avoid duplicating code in subclasses.
Design a class that represents the common state and behavior
All Animals – have a picture; eat food, have hunger, etc.Slide7
Inheritance Tree, cont’d
Decide if a subclass needs behaviors (method implementations) that are specific to that particular subclass type.
MakeNoise
and Eat are specific to each type of animal.
Look for more opportunities to use abstraction, by finding two or more
subclasses
that might need common behavior
.Slide8
Page 174
Finish the class Hierarchy
Since animals already have an organizational hierarchy, that makes the most sense for class design.
Felines – lion, tiger, cat (can use a common roam method)
Canine – wolf, dog (can use a common roam method)Slide9