2012 Pearson Education Inc All rights reserved Chapter

  • Slides: 47
Download presentation
© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with

© 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

Inheritance (Chapter 11) – Topics • • • What Is Inheritance? Calling the Superclass

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -2

11. 1. What is Inheritance? Generalization vs. Specialization • Real-life objects are typically specialized

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -3

Inheritance Insect Contains attributes and methods shared by all insects. (a superclass) Bumble. Bee

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

The “is a” Relationship • The “is a” relationship — the relationship between a

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -5

The “is a” Relationship • Inheritance involves: – a superclass = a general class

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -6

Inheritance • The subclass inherits fields and methods from the superclass – without any

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 Final. Exam extends Graded. Activity © 2012 Pearson Education, Inc. All rights reserved. 11 -7

The Graded. Activity Example Graded. Activity - score : double + set. Score(s :

The Graded. Activity Example Graded. Activity - score : double + set. Score(s : double) : void + get. Score() : double + get. Grade() : char NOTE: “-” = private attribute/method “+” = public attribute/method Contains attributes and methods shared by all graded activities. Inherits all non-private attributes and methods from Graded. Activity. Contains attributes and methods specific to Final. Exam. Fina. Exam - num. Questions : int - points. Each : double - num. Missed : int + Final. Exam(questions : int, missed : int) + get. Points. Each() : double + get. Num. Missed() : int © 2012 Pearson Education, Inc. All rights reserved. • Example: – – Graded. Activity. java, Grade. Demo. java, Final. Exam. Demo. java 11 -8

Inheritance, Fields and Methods • Private members of the superclass: – are not inherited

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -9

Inheritance, Fields and Methods • When a subclass instance is created, the non-private methods

Inheritance, Fields and Methods • When a subclass instance is created, the non-private methods of the superclass are available through the subclass object. Final. Exam exam = new Final. Exam(); exam. set. Score(85. 0); // set. Score is non-private // in superclass System. out. println("Score = " + exam. get. Score()); • Non-private methods and fields of the superclass are available in the subclass. set. Score(numeric. Score); © 2012 Pearson Education, Inc. All rights reserved. 11 -10

Inheritance and Constructors • Constructors are not inherited • When a subclass is instantiated,

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: • Super. Class 1. java • Sub. Class 1. java • Constructor. Demo 1. java © 2012 Pearson Education, Inc. All rights reserved. 11 -11

11. 2. Calling the Superclass’s Constructor • The super keyword refers to an object’s

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: • Super. Class 2. java, Sub. Class 2. java, Constructor. Demo 2. java ++READ++ • Rectangle. java, Cube. Demo. java © 2012 Pearson Education, Inc. All rights reserved. 11 -12

Calling The Superclass Constructor • A superclass may have parameterized constructors only • That

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -13

Calling The Superclass Constructor – cont. • If a superclass has (only) parameterized constructors,

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -14

Calling The Superclass Constructor – cont. • If >1 superclass constructors, which one is

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -15

11. 3. Overriding Superclass Methods • Recall that a method signature consists of: –

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: – Graded. Activity. java, includes the method: public void repl(int num, String id) – Its signature: repl(int, String) © 2014 Leszek T. Lilien © 2012 Pearson Education, Inc. All rights reserved. 11 -16

Overriding Superclass Methods • A subclass may have a method with the same signature

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: – Graded. Activity. java, Curved. Activity. Demo. java © 2012 Pearson Education, Inc. All rights reserved. 11 -17

Overriding Superclass Methods Graded. Activity - score : double + set. Score(s : double)

Overriding Superclass Methods Graded. Activity - score : double + set. Score(s : double) : void + get. Score() : double + get. Grade() : char Curved. Activity - raw. Score : double - percentage : double This setscore method is a more specialized version of the set. Score method in the superclass. + Curved. Activity(percent : double) + set. Score(s : double) : void + get. Raw. Score() : double + get. Percentage() : double © 2012 Pearson Education, Inc. All rights reserved. 11 -18

Overriding Superclass Methods • A subclass method that overrides a superclass method must have

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) © 2012 Pearson Education, Inc. All rights reserved. 11 -19

Overriding Superclass Methods • An subclass method can call the overridden superclass method via

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

Overriding vs. Overloading • Overloading a method vs. overriding a method – Overloading is

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: – Super. Class 3. java, – Sub. Class 3. java, – Show. Value. Demo. java © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -21

Preventing a Method from Being Overridden • The final modifier will prevent the overriding

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. © 2012 Pearson Education, Inc. All rights reserved. 11 -22

11. 4. Protected Members • Java provides a third access specification, protected – In

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: – Graded. Activity 2. java – Final. Exam 2. java – Protected. Demo. java © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -23

Protected Members • Avoid the protected access specificaton – Using protected instead of private

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -24

Access Specifiers Access Modifier Accessible to a subclass inside the same package? Accessible to

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 Public Yes Protected Yes Private No No Accessible to a subclass outside the package? Access Modifier Accessible to all other classes outside the package? default (no modifier) No No Public Yes Protected Yes No Private No No © 2012 Pearson Education, Inc. All rights reserved. 11 -25

++READ++ 11. 5. Chains of Inheritance • A superclass can be a subclass of

++READ++ 11. 5. Chains of Inheritance • A superclass can be a subclass of another class. Object Example: Graded. Activity. java Pass. Fail. Exam. Demo. java Graded. Activity Pass. Fail. Exam © 2012 Pearson Education, Inc. All rights reserved. 11 -26

++READ++ Chains of Inheritance • Classes often are depicted graphically in a class hierarchy.

++READ++ Chains of Inheritance • Classes often are depicted graphically in a class hierarchy. • A class hierarchy shows the inheritance relationships between classes. Graded. Activity Final. Exam Pass. Fail. Activity Pass. Fail. Exam © 2012 Pearson Education, Inc. All rights reserved. 11 -27

11. 6. The Object Class • All Java classes are directly or indirectly derived

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 My. Class extends Object { // This class is explicitly derived from Object. } © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -28

The Object Class • Every class inherits the Object class’s members. – Because every

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 to. String and equals methods – to. String 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: Object. Methods. java © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -29

11. 7. Polymorphism Graded. Activity Final. Exam • Declare a reference variable for a

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

Polymorphism • REPEATING: a superclass Graded. Activity reference variable may be used to reference

Polymorphism • REPEATING: a superclass Graded. Activity reference variable may be used to reference a subclass Final. Exam object Graded. Activity exam = new Final. Exam(50, 7); • This statement creates a Final. Exam 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 © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -31

Polymorphism Graded. Activity Final. Exam • Other legal polymorphic references: Pass. Fail. Activity Pass.

Polymorphism Graded. Activity Final. Exam • Other legal polymorphic references: Pass. Fail. Activity Pass. Fail. Exam Graded. Activity exam 1 = new Final. Exam(50, 7); Graded. Activity exam 2 = new Pass. Fail. Activity(70); Graded. Activity exam 3 = new Pass. Fail. Exam(100, 10, 70); • The Graded. Activity class has three methods: set. Score, get. Score, and get. Grade. • A Graded. Activity variable can be used to call only its three methods (not any method of any of its subclass) Graded. Activity exam = new Pass. Fail. Exam(100, 10, 70); System. out. println(exam. get. Score()); // This works. System. out. println(exam. get. Grade()); // This works. System. out. println(exam. get. Points. Each()); // ERROR! A PFE method © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -32

Polymorphism and Dynamic Binding Graded. Activity Final. Exam Pass. Fail. Activity Pass. Fail. Exam

Polymorphism and Dynamic Binding Graded. Activity Final. Exam Pass. Fail. Activity Pass. Fail. Exam • 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 Graded. Activity exam = new Pass. Fail. Activity(60); exam. set. Score(70); // set. Score in GA not in PFA System. out. println(exam. get. Grade()); // get. Grade in GA and in PFA; JVM calls PFA’s get. Grade • 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 © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -33

Polymorphism • The object’s type (not the reference type) determines which method is called

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

The instanceof operator • See textbook, p. 701 © 2014 Lilien 2012 Leszek Pearson.

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

11. 8. Abstract Classes and Abstract Methods Abstract Classes • An abstract class cannot

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 Class. Name © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -36

Abstract Methods • An abstract class may include abstract methods • An abstract method

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 Access. Specifier abstract Return. Type Method. Name(Params); e. g. : public abstract void set. Value(int value); • Example: – Student. java, Comp. Sci. Student. Demo. java © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -37

Abstract Methods • Notice that the key word abstract appears in the header, and

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 © 2012 Pearson Education, Inc. All rights reserved. 11 -38

11. 9. Interfaces • An interface is similar to an abstract class that has

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 Interface. Name { (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 © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -39

Interfaces • A class can implement one or more interfaces. • Example: A class

Interfaces • A class can implement one or more interfaces. • Example: A class implementing an interface - the implements keyword public class Final. Exam 3 extends Graded. Activity implements Relatable • Example: – – Graded. Activity. java Relatable. java Final. Exam 3. java Interface. Demo. java © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -40

Fields in Interfaces • An interface can contain field declarations: – All fields in

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 FIELD 1 = 1, FIELD 2 = 2; (Method headers. . . ) } – FIELD 1 and FIELD 2 are final static int variables. – Any class that implements this interface has access to these variables. © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -41

Implementing Multiple Interfaces • A class can implement multiple interfaces – In contrast, a

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

Interfaces in UML (see p. 715) Graded. Activity Final. Exam 3 © 2012 Pearson

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

Polymorphism with Interfaces • Java interface reference variable – It can reference any object

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 Compact. Disc and Dvd. Movie realize the Retail. Item interface Retail. Item item 1 = new Compact. Disc( “Songs from the Hart”, “Billy Nelson”, 18. 95); Retail. Item item 2 = new Dvd. Movie( “Planet X”, 102, 22. 95); – In the example code, two Retail. Item reference variables, item 1 and item 2, are declared. – The item 1 variable references a Compact. Disc object and the item 2 variable references a Dvd. Movie object © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -44

Polymorphism with Interfaces • When a class implements an interface, an inheritance relationship known

Polymorphism with Interfaces • When a class implements an interface, an inheritance relationship known as interface inheritance is established – For example: • any Compact. Disc object (incl. item 1) is a Retail. Item, and • any Dvd. Movie object (incl. item 2) is a Retail. Item • Example: – – Retail. Item. java Compact. Disc. java Dvd. Movie. java Polymorphic. Interface. Demo. java © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -45

Polymorphism with Interfaces • An interface reference variable can refer to any class that

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 Retail. Item item = new Retail. Item(); // 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 © 2012 Pearson Education, Inc. All rights reserved. Updated by L. Lilien 11 -46

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

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