Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second.

Similar presentations


Presentation on theme: "© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second."— Presentation transcript:

1 © 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second Edition by Tony Gaddis and Godfrey Muganda With formatting and other updates by Dr. L. Lilien

2 © 2012 Pearson Education, Inc. All rights reserved. 11-2 Inheritance (Chapter 11) – Topics What Is Inheritance? Calling the Superclass Constructor Overriding Superclass Methods Protected Members Chains of Inheritance The Object Class Polymorphism Abstract Classes and Abstract Methods Interfaces

3 © 2012 Pearson Education, Inc. All rights reserved. 11-3 11.1. What is Inheritance? Generalization vs. Specialization Real-life objects are typically specialized versions of other more general objects NEXT PAGE - Example : –Insect -- a very general type of creature (with numerous characteristics) –Grasshoppers and bumblebees are insects They share the general characteristics of an insect. However, they have special characteristics of their own: –grasshoppers -- a jumping ability –bumblebees -- a stinger Grasshoppers and bumblebees are specialized versions of an insect

4 © 2012 Pearson Education, Inc. All rights reserved. 11-4 Inheritance Insect (a superclass) Grasshopper (an inherited class) BumbleBee (an inherited class) Contains attributes and methods shared by all insects. Contains attributes and methods specific to a Bumble Bee (a stinger, …) Contains attributes and methods specific to a Grasshopper (jumping ability,...)

5 © 2012 Pearson Education, Inc. All rights reserved. 11-5 The “is a” Relationship The “is a” relationship — the relationship between a superclass and an inherited class –A grasshopper “is an” insect –A poodle “is a” dog –A car “is a” vehicle Characteristics of a specialized object include: –Those of its general object, plus –Those that make it special In object-oriented programming, inheritance used to create an “is a” relationship among classes

6 © 2012 Pearson Education, Inc. All rights reserved. 11-6 The “is a” Relationship Inheritance involves: –a superclass = a general class = a “parent” class –a subclass = a specialized class = a “child” class A subclass extends (is based on) its superclass. –a superclass = a base class –a subclass = a derived class

7 © 2012 Pearson Education, Inc. All rights reserved. 11-7 Inheritance The subclass inherits fields and methods from the superclass –without any of them being rewritten In addition, the subclass may have new fields and methods The Java keyword extends is used on the class header to define the subclass. public class FinalExam extends GradedActivity

8 © 2012 Pearson Education, Inc. All rights reserved. 11-8 The GradedActivity Example Example: –GradedActivity.java,GradedActivity.java –GradeDemo.java,GradeDemo.java –FinalExam.java,FinalExam.java –FinalExamDemo.javaFinalExamDemo.java GradedActivity - score : double + setScore(s : double) : void + getScore() : double + getGrade() : char FinaExam - numQuestions : int - pointsEach : double - numMissed : int + FinalExam(questions : int, missed : int) + getPointsEach() : double + getNumMissed() : int Contains attributes and methods shared by all graded activities. Inherits all non-private attributes and methods from GradedActivity. Contains attributes and methods specific to FinalExam. NOTE: “-” = private attribute/method “+” = public attribute/method

9 © 2012 Pearson Education, Inc. All rights reserved. 11-9 Inheritance, Fields and Methods Private members of the superclass: –are not inherited by the subclass –exist in memory when the object of the subclass is created –subclass may accessed them only via public methods of the superclass Public members of the superclass: –are inherited by the subclass –may be directly accessed from the subclass

10 © 2012 Pearson Education, Inc. All rights reserved. 11-10 Inheritance, Fields and Methods When a subclass instance is created, the non-private methods of the superclass are available through the subclass object. FinalExam exam = new FinalExam(); exam.setScore(85.0); // setScore is non-private // in superclass System.out.println("Score = " + exam.getScore()); Non-private methods and fields of the superclass are available in the subclass. setScore(numericScore);

11 © 2012 Pearson Education, Inc. All rights reserved. 11-11 Inheritance and Constructors Constructors are not inherited When a subclass is instantiated, the superclass default constructor (provided by Java) or no-argument constructor (provided by programmer) is executed first (before the subclass’s own constructor) –Example: SuperClass1.java SubClass1.java ConstructorDemo1.java

12 © 2012 Pearson Education, Inc. All rights reserved. 11-12 11.2. Calling the Superclass’s Constructor The super keyword refers to an object’s superclass The superclass constructor can be explicitly called from the subclass by using the super keyword. –Examples: SuperClass2.java, SubClass2.java, ConstructorDemo2.javaSuperClass2.javaSubClass2.java ConstructorDemo2.java ++READ++ Rectangle.java, Cube.java, CubeDemo.javaRectangle.javaCube.javaCubeDemo.java

13 © 2012 Pearson Education, Inc. All rights reserved. 11-13 Calling The Superclass Constructor A superclass may have parameterized constructors only That is, no programmer-provided no-argument constructor –In this case, Java does not provide a default constructor automatically RECALL: Java provides the default constructor only when a class has no programmer-provided constructors (parametrized or not) © 2014 Leszek T. Lilien

14 © 2012 Pearson Education, Inc. All rights reserved. 11-14 Calling The Superclass Constructor – cont. If a superclass has (only) parameterized constructors, (does not have deafult constructor or no-argument constructor), –subclasses must provide constructors AND –each subclass constructor must call one of constructors of the superclass © 2014 Leszek T. Lilien

15 © 2012 Pearson Education, Inc. All rights reserved. 11-15 Calling The Superclass Constructor – cont. If >1 superclass constructors, which one is called when subclass object created? –A subclass can explicitly call a selected superclass constructor with the super keyword This call must be the first Java statement in the subclass constructor © 2014 Leszek T. Lilien

16 © 2012 Pearson Education, Inc. All rights reserved. 11-16 11.3. Overriding Superclass Methods Recall that a method signature consists of: –the method’s name –the data types of method’s parameters in the order that they appear Example: –GradedActivity.java, includes the method:GradedActivity.java public void repl(int num, String id) –Its signature: repl(int, String) © 2014 Leszek T. Lilien

17 © 2012 Pearson Education, Inc. All rights reserved. 11-17 Overriding Superclass Methods A subclass may have a method with the same signature as a superclass method. –In this case, the subclass method overrides the superclass method Example of method overriding: –GradedActivity.java, CurvedActivity.java, CurvedActivityDemo.javaGradedActivity.javaCurvedActivity.java CurvedActivityDemo.java

18 © 2012 Pearson Education, Inc. All rights reserved. 11-18 Overriding Superclass Methods GradedActivity - score : double + setScore(s : double) : void + getScore() : double + getGrade() : char CurvedActivity - rawScore : double - percentage : double + CurvedActivity(percent : double) + setScore(s : double) : void + getRawScore() : double + getPercentage() : double This setscore method is a more specialized version of the setScore method in the superclass.

19 © 2012 Pearson Education, Inc. All rights reserved. 11-19 Overriding Superclass Methods A subclass method that overrides a superclass method must have the same signature as the superclass method being overriden –An object of the subclass invokes the subclass’s version of the method, not the superclass’s Unless super.method_name used (next slide)

20 © 2012 Pearson Education, Inc. All rights reserved. 11-20 Overriding Superclass Methods An subclass method can call the overridden superclass method via the super keyword. super.setScore(rawScore * percentage); Updated by L. Lilien

21 © 2012 Pearson Education, Inc. All rights reserved. 11-21 Overriding vs. Overloading Overloading a method vs. overriding a method –Overloading is when a method has the same name as one or more other methods, but with a different signature –When a method overrides another method, however, they both have the same signature Overloading and overriding can take place in an inheritance relationship –Overriding - only in an inheritance relationship Example: –SuperClass3.java,SuperClass3.java –SubClass3.java,SubClass3.java –ShowValueDemo.javaShowValueDemo.java Updated by L. Lilien

22 © 2012 Pearson Education, Inc. All rights reserved. 11-22 Preventing a Method from Being Overridden The final modifier will prevent the overriding of a superclass method in a subclass. public final void message() If a subclass attempts to override a final method, the compiler generates an error. –Ensures that a particular superclass method is used by subclasses rather than an overriding version of it.

23 © 2012 Pearson Education, Inc. All rights reserved. 11-23 11.4. Protected Members Java provides a third access specification, protected –In addition to public and private –A protected member’s access is somewhere between private and public. In UML diagrams, indicated with # Protected members of class: –may be accessed by methods in a subclass, and –by methods in the same package as the class Example: –GradedActivity2.javaGradedActivity2.java –FinalExam2.javaFinalExam2.java –ProtectedDemo.javaProtectedDemo.java Updated by L. Lilien

24 © 2012 Pearson Education, Inc. All rights reserved. 11-24 Protected Members Avoid the protected access specificaton –Using protected instead of private makes some tasks easier –However, any class that is derived from the class, or is in the same package, has unrestricted access to the protected member It is always better to make all fields private and then provide public methods for accessing those fields If no access specifier for a class member is provided, the class member is given package access by default –Any method in the same package may access the member

25 © 2012 Pearson Education, Inc. All rights reserved. 11-25 Access Specifiers Access Modifier Accessible to a subclass inside the same package? Accessible to all other classes inside the same package? default (no modifier) Yes PublicYes ProtectedYes PrivateNo Access Modifier Accessible to a subclass outside the package? Accessible to all other classes outside the package? default (no modifier) No PublicYes ProtectedYesNo PrivateNo

26 © 2012 Pearson Education, Inc. All rights reserved. 11-26 ++READ++ 11.5. Chains of Inheritance A superclass can be a subclass of another class. Object PassFailActivity PassFailExam GradedActivity Example: GradedActivity.java PassFailActivity.java PassFailExam.java PassFailExamDemo.java GradedActivity.java PassFailActivity.java PassFailExam.java PassFailExamDemo.java

27 © 2012 Pearson Education, Inc. All rights reserved. 11-27 ++READ++ Chains of Inheritance Classes often are depicted graphically in a class hierarchy. A class hierarchy shows the inheritance relationships between classes. PassFailActivity PassFailExam GradedActivity FinalExam

28 © 2012 Pearson Education, Inc. All rights reserved. 11-28 11.6. The Object Class All Java classes are directly or indirectly derived from a class named Object –Object is in the java.lang package –Any class that does not specify the extends keyword is automatically derived from the Object class Example: public class myclass { // This class is implicitly derived from Object. } The above class is equivalent to: public class MyClass extends Object { // This class is explicitly derived from Object. } Updated by L. Lilien

29 © 2012 Pearson Education, Inc. All rights reserved. 11-29 The Object Class Every class inherits the Object class’s members. –Because every class is directly or indirectly derived from the Object class Every class inherits Object class’s toString and equals methods –toString returns a string containing the object’s class name and a hash of its memory address –equals checks if 2 object references denote the same object equals accepts the address of an object as its argument and returns true if it is the same as the calling object’s address Example: ObjectMethods.javaObjectMethods.java Updated by L. Lilien

30 © 2012 Pearson Education, Inc. All rights reserved. 11-30 11.7. Polymorphism Declare a reference variable for a superclass GradedActivity exam; // It can (obviously) reference a superclass object exam = new GradedActivity(); FinalExam is a subclass of GradedActivity –So, any FinalExam subclass object is-a GradedActivity superclass object –Therefore, a superclass GradedActivity variable may be used to reference a subclass FinalExam object GradedActivity exam = new FinalExam(50, 7); PassFailActivity PassFailExam GradedActivity FinalExam © 2014 Leszek T. Lilien

31 © 2012 Pearson Education, Inc. All rights reserved. 11-31 Polymorphism REPEATING: a superclass GradedActivity reference variable may be used to reference a subclass FinalExam object GradedActivity exam = new FinalExam(50, 7); This statement creates a FinalExam object and stores the object’s address in the exam variable (of the superclass type) –This is an example of polymorphism polymorphism = the ability to take many forms In Java, a reference variable is polymorphic because it can reference objects of types different from its own, as long as those types are subclasses of its type Updated by L. Lilien

32 © 2012 Pearson Education, Inc. All rights reserved. 11-32 Polymorphism Other legal polymorphic references: GradedActivity exam1 = new FinalExam(50, 7); GradedActivity exam2 = new PassFailActivity(70); GradedActivity exam3 = new PassFailExam(100, 10, 70); The GradedActivity class has three methods: setScore, getScore, and getGrade. A GradedActivity variable can be used to call only its three methods (not any method of any of its subclass) GradedActivity exam = new PassFailExam(100, 10, 70); System.out.println(exam.getScore()); // This works. System.out.println(exam.getGrade()); // This works. System.out.println(exam.getPointsEach()); // ERROR! A PFE method PassFailActivity PassFailExam GradedActivity FinalExam Updated by L. Lilien

33 © 2012 Pearson Education, Inc. All rights reserved. 11-33 Polymorphism and Dynamic Binding Suppose that a subclass has overridden a method in the superclass: –Then, if the variable makes a call to that method the subclass’s version of the method will be run GradedActivity exam = new PassFailActivity(60); exam.setScore(70); // setScore in GA not in PFA System.out.println(exam.getGrade()); // getGrade in GA and in PFA; JVM calls PFA’s getGrade Java performs dynamic binding or late binding when a variable contains a polymorphic reference –The Java Virtual Machine (JVM) determines at runtime which method to call Depending on the type of object that the variable references Updated by L. Lilien PassFailActivity PassFailExam GradedActivity FinalExam

34 © 2012 Pearson Education, Inc. All rights reserved. 11-34 Polymorphism The object’s type (not the reference type) determines which method is called GradedActivity exam = new PassFailActivity(60); // exam is an object of type PFA System.out.println(exam.getGrade()); // getGrade in both GA and in PFA // JVM calls PFA’s getGrade since the object exam // is of type PFA (although the exam reference // variable is of superclass type GA) Example: –Polymorphic.javaPolymorphic.java You cannot assign a superclass object to a subclass reference variable Updated by L. Lilien

35 © 2012 Pearson Education, Inc. All rights reserved. 11-35 The instanceof operator See textbook, p.701 © 2014 Leszek T. Lilien

36 © 2012 Pearson Education, Inc. All rights reserved. 11-36 11.8. Abstract Classes and Abstract Methods Abstract Classes An abstract class cannot be instantiated –But still serves as a superclass for other classes –Represents the generic or abstract form of all the classes that are derived from it Indicated with the abstract keyword in the class definition public abstract class ClassName Updated by L. Lilien

37 © 2012 Pearson Education, Inc. All rights reserved. 11-37 Abstract Methods An abstract class may include abstract methods An abstract method has no body (only a header) It must be overridden in a subclass AccessSpecifier abstract ReturnType MethodName(Params); e.g.: public abstract void setValue(int value); Example: –Student.java, CompSciStudent.java, CompSciStudentDemo.javaStudent.javaCompSciStudent.javaCompSciStudentDemo.java Updated by L. Lilien

38 © 2012 Pearson Education, Inc. All rights reserved. 11-38 Abstract Methods Notice that the key word abstract appears in the header, and that the header ends with a semicolon. Any class that contains an abstract method is automatically abstract If a subclass fails to override an abstract method, a compiler error will result Abstract methods are used to ensure that a subclass implements the method

39 © 2012 Pearson Education, Inc. All rights reserved. 11-39 11.9. Interfaces An interface is similar to an abstract class that has all abstract methods (not just some abstract methods, as an abstract class) –The keyword interface indicates an interface public interface InterfaceName { (Method headers...) } –An interface cannot be instantiated –All of the methods of an interface must be written elsewhere They have no bodies, only headers –All methods in an interface are public by default The purpose of an interface: to specify behavior for other classes Updated by L. Lilien

40 © 2012 Pearson Education, Inc. All rights reserved. 11-40 Interfaces A class can implement one or more interfaces. Example: A class implementing an interface - the implements keyword public class FinalExam3 extends GradedActivity implements Relatable Example: –GradedActivity.javaGradedActivity.java –Relatable.javaRelatable.java –FinalExam3.javaFinalExam3.java –InterfaceDemo.javaInterfaceDemo.java Updated by L. Lilien

41 © 2012 Pearson Education, Inc. All rights reserved. 11-41 Fields in Interfaces An interface can contain field declarations: –All fields in an interface are final and static Because they are final, you must initialize them public interface Doable { int FIELD1 = 1, FIELD2 = 2; (Method headers...) } –FIELD1 and FIELD2 are final static int variables. –Any class that implements this interface has access to these variables. Updated by L. Lilien

42 © 2012 Pearson Education, Inc. All rights reserved. 11-42 Implementing Multiple Interfaces A class can implement multiple interfaces –In contrast, a class can be derived from only one superclass public class MyClass implements Interface1, Interface2, Interface3 When a class implements multiple interfaces, it must provide the methods specified by all of them Updated by L. Lilien

43 © 2012 Pearson Education, Inc. All rights reserved. 11-43 Interfaces in UML (see p. 715) GradedActivity > Relatable FinalExam3 1) A dashed arrow indicates implementation of an interface (known as a realization—the class realizes the interface). 2) The > tag precedes the interface name. 3) The interface name in italics. Updated by L. Lilien

44 © 2012 Pearson Education, Inc. All rights reserved. 11-44 Polymorphism with Interfaces Java interface reference variable –It can reference any object that implements that interface, regardless of its class type This is interface polymorphism –Example: Assume that classes CompactDisc and DvdMovie realize the RetailItem interface RetailItem item1 = new CompactDisc( “Songs from the Hart”, “Billy Nelson”, 18.95); RetailItem item2 = new DvdMovie( “Planet X”, 102, 22.95); –In the example code, two RetailItem reference variables, item1 and item2, are declared. –The item1 variable references a CompactDisc object and the item2 variable references a DvdMovie object Updated by L. Lilien

45 © 2012 Pearson Education, Inc. All rights reserved. 11-45 Polymorphism with Interfaces When a class implements an interface, an inheritance relationship known as interface inheritance is established –For example: any CompactDisc object (incl. item1 ) is a RetailItem, and any DvdMovie object (incl. item2 ) is a RetailItem Example: –RetailItem.javaRetailItem.java –CompactDisc.javaCompactDisc.java –DvdMovie.javaDvdMovie.java –PolymorphicInterfaceDemo.javaPolymorphicInterfaceDemo.java Updated by L. Lilien

46 © 2012 Pearson Education, Inc. All rights reserved. 11-46 Polymorphism with Interfaces An interface reference variable can refer to any class that implements (realizes) that interface You cannot create an instance of an interface RetailItem item = new RetailItem(); // ERROR! When an interface variable references an object: –Only the methods declared in the interface are available –Explicit type casting is required to access the other methods of an object referenced by an interface reference See example on p.720 Updated by L. Lilien

47 © 2012 Pearson Education, Inc. All rights reserved. 11-47 The End


Download ppt "© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second."

Similar presentations


Ads by Google