Topic6Topic 6Inheritance andInheritance and Polymorphism"Question: What is the object oriented way of getting rich?Answer: Inheritance.““Inheritance is new code that reuses old codeInheritance is new code that reuses old code.Polymorphism is old code that reuses new code.”CS 307 Fundamentals of Computer Science Inheritance and Polymorphism1OutlineExplanation of inheritance.Using inheritance to create a SortedIntList.Explanation of polymorphism.Using polymorphism to make a more genericUsing polymorphism to make a more generic List class.CS 307 Fundamentals of Computer Science Inheritance and Polymorphism2Explanation of InheritanceExplanation of InheritanceCS 307 Fundamentals of Computer Science Inheritance and Polymorphism3Main Tenets of OO ProgrammingEncapsulation–abstraction, information hidingabs ac o , o a o d gInheritancecode reuse specialization"New code using old–code reuse, specialization New code using old code."PolymorphismPolymorphism– do X for a collection of various types of objects, where X isdifferentdepending on the type ofwhere X is differentdepending on the type of object–"Old code using new code"CS 307 Fundamentals of Computer Science Inheritance and Polymorphism4Old code using new code.Things and RelationshipsObjtitd i ldtObject oriented programming leads to programs that are modelsti d l f thi i th l ld–sometimes models of things in the real world– sometimes models of contrived or imaginary thingsThere are many types of relationships betweenThere are many types of relationships between the things in the modelschess piece has a position–chess piece has a position– chess piece has a colorchess piece moves (changes position)–chess piece moves (changes position)– chess piece is taken–arookisatypeofchesspieceCS 307 Fundamentals of Computer Science Inheritance and Polymorphism5a rook is a type of chess pieceThe “has-A” RelationshipObjects are often made up of many parts or have sub data.– chess piece: position, color– die: result, number of sidesThis “has-a” relationship is modeled by compositionp– the instance variables or fields internal to objectsEncapsulation captures this conceptEncapsulation captures this conceptCS 307 Fundamentals of Computer Science Inheritance and Polymorphism6The “is-a” relationshipAnother type of relationship found in the real world– a rook is a chess piece– a queen is a chess piece– a student is a person– a faculty member is a person– an undergraduate student is a student“is-a”usually denotes some form ofisa usually denotes some form of specializationit is not the same as“has-a”CS 307 Fundamentals of Computer Science Inheritance and Polymorphism7it is not the same as has-aInheritanceThe “is-a” relationship, and the specialization that accompanies it, is modeled in object oriented languages via inheritanceClasses can inherit from other classes– base inheritance in a program on the real world things being modeled– does “an A is a B” make sense? Is it logical?CS 307 Fundamentals of Computer Science Inheritance and Polymorphism8Nomenclature of InheritanceIJ thtdkdidithIn Java the extendskeyword is used in the class header to specify which preexisting class a new class is inheriting fromae casss e gopublic class Student extends Person Person is said to be hlfSd–the parent class of Student– the super class of Student– the base class of Student–an ancestor of Student Student is said to be–a child class of Person– a sub class of Person– a derived class of Person–a descendant of PersonCS 307 Fundamentals of Computer Science Inheritance and Polymorphism9Results of Inheritancepublic class Apublic class B extends Athe sub class inherits (gains) all instance variables and instance methods of the super a ab es a d sta ce et ods o t e supeclass, automaticallyadditional methods can be added to class Badditional methods can be added to class B (specialization)the sub class can replace (redefinethe sub class can replace (redefine, override) methods from the super classCS 307 Fundamentals of Computer Science Inheritance and Polymorphism10Attendance Question 1What is the primary reason for using inheritance when programming?A. To make a program more complicatedB. To duplicate code between classesC Toreusepre-existing codeC. To reuse pre-existing codeD. To hide implementation details of a classEE. To ensure pre conditions of methods are met.CS 307 Fundamentals of Computer Science Inheritance and Polymorphism11Inheritance in JavaJava is a pure object oriented languageJava is a pure object oriented language all code is part of some classall classes except one must inherit fromall classes, except one, must inherit from exactly one other classTheObjectclass is thecosmic super classThe Objectclass is the cosmic super class– The Object class does not inherit from any other class– The Object class has several important methods:toString, equals, hashCode, clone, getClass implications:all classes are descendants ofObject–all classes are descendants of Object– all classes and thus all objects have a toString, equals, hashCode, clone, and getClass methodCS 307 Fundamentals of Computer Science Inheritance and Polymorphism12• toString, equals, hashCode, clone normally overriddenInheritance in JavaIf l h d d t i l d thIf a class header does not include the extends clause the class extends the Obj tclass by defaultObjectclass by defaultpublic class Dieilll– Objectis an ancestor to all classes– it is the only class that does not extend some th lother classA class extends exactly one other class– extending two or more classes is multiple inheritance. Java does not support this directly, th itIt fCS 307 Fundamentals of Computer Science Inheritance and Polymorphism13rather it uses Interfaces.Overriding methodsany method that is not final may be overridden by a descendant classysame signature as method in ancestormay not reduce visibilitymay not reduce visibilitymay use the original method if simply want to dd b h i t i tiadd more behavior to existingCS 307 Fundamentals of Computer Science Inheritance and Polymorphism14Attendance Question 2What is output when the main method is run?public class Foo{public static void main(String[] args){Foo f1 = new Foo();System.out.println( f1.toString() );}}}A. 0BnullB. nullC. Unknown until code is
View Full Document