90 likes | 218 Views
Inheritance, Superclasses , Subclasses. 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
E N D
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.
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.
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
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 method
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.
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.
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)