Chapter 9 Inheritance Chapter Goals To learn about

Chapter 9 – Inheritance

Chapter Goals To learn about inheritance To implement subclasses that inherit and override superclass methods To understand the concept of polymorphism To be familiar with the common superclass Objectand its methods

Inheritance Hierarchies Inheritance: the relationship between a more general class (superclass) and a more specialized class (subclass). The subclass inherits data and behavior from the superclass. Cars share the common traits of all vehicles Example: the ability to transport people from one place to another Figure 1 An Inheritance Hierarchy of Vehicle Classes

Inheritance Hierarchies The class Carinherits from the class Vehicle The Vehicleclass is the superclass The Carclass is the subclass Figure 2 Inheritance Diagram

Inheritance Hierarchies Inheritance lets you can reuse code instead of duplicating it. Two types of reuse A subclass inherits the methods of the superclass Because a car is a special kind of vehicle, we can use a Carobject in algorithms that manipulate Vehicleobjects The substitution principle: You can always use a subclass object when a superclass object is expected. A method that processes Vehicleobjects can handle any kind of vehicle

Inheritance Hierarchies Figure 3 Inheritance Hierarchy of Question Types Example: Computer-graded quiz There are different kinds of questions A question can display its text, and it can check whether a given response is a correct answer. You can form subclasses of the Questionclass.

s ection_1/ Q ues tion. java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /** A question with a text and an answer. */ public class Question { private String text; private String answer; /** Constructs a question with empty question and answer. */ public Question() { text = ""; answer = ""; } /** Sets the question text. @param question. Text the text of this question */ public void set. Text(String question. Text) { text = question. Text; } /** Sets the answer for this question. @param correct. Response the answer */ public void set. Answer(String correct. Response) {

section_1/Question. Demo 1. java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java. util. Scanner; /** This program shows a simple quiz with one question. */ public class Question. Demo 1 { public static void main(String[] args) { Scanner in = new Scanner(System. in); Question q = new Question(); q. set. Text("Who was the inventor of Java? "); q. set. Answer( "James Gosling"); } q. display(); System. out. print( "Your answer: "); String response = in. next. Line(); System. out. println(q. check. Answer(response)); } Program Run: Who was the inventor of Java? Your answer: James Gosling true

Implementing Subclasses Like the manufacturer of a stretch limo, who starts with a regular car and modifies it, a programmer makes a subclass by modifying another class. To get a Choice. Questionclass, implement it as a subclass of Question Specify what makes the subclass different from its superclass. Subclass objects automatically have the instance variables that are declared in the superclass. Only declare instance variables that are not part of the superclass objects. A subclass inherits all methods that it does not override. Figure 4 The Choice. Question. Class is a Subclass of the Question Class.

Implementing Subclasses The subclass inherits all public methods from the superclass. You declare any methods that are new to the subclass. You change the implementation of inherited methods if the inherited behavior is not appropriate. Override a method: supply a new implementation for an inherited method

Implementing Subclasses A Choice. Questionobject differs from a Questionobject in three ways: Its objects store the various choices for the answer. There is a method for adding answer choices. The display method of the Choice. Questionclass shows these choices so that the respondent can choose one of them.

Implementing Subclasses The Choice. Questionclass needs to spell out the three differences: public class Choice. Question extends Question { // This instance variable is added to the subclass private Array. List<String> choices; // This method is added word to the subclass The extends reserved indicates that a class inherits from a superclass. public void add. Choice(String choice, boolean correct) {. . . } // This method overrides a method from the superclass public void display() {. . . } }

Implementing Subclasses UML of Choice. Questionand Question Figure 5 The Choice. Question. Class Adds an Instance Variable and a Method, and Overrides a Method

Syntax 9. 1 Subclass Declaration

Implementing Subclasses A Choice. Questionobject You can call the inherited methods on a subclass object: choice. Question. set. Answer("2"); The private instance variables of the superclass are inaccessible. The Choice. Questionmethods cannot directly access the instance variable answer. Choice. Questionmethods must use the public interface of the Question class to access its private data.

Implementing Subclasses Adding a new method: add. Choice public void add. Choice(String choice, boolean correct) { choices. add(choice); if (correct) { // Convert choices. size() to string String choice. String = "" + choices. size(); set. Answer(choice. String); } } add. Choicemethod can not just access the answervariable in the superclass: It must use the set. Answermethod Invoke set. Answeron the implicit parameter: set. Answer(choice. String); OR this. set. Answer(choice. String);

Common Error: Replicating Instance Variables from the Superclass A subclass has no access to the private instance variables of the superclass: public Choice. Question(String question. Text) { text = question. Text; // Error—tries to access private superclass variable } Beginner's error: "solve" this problem by adding another instance variable with same name Error! public class Choice. Question extends Question { private Array. List<String> choices; private String text; // Don’t!. . . } The constructor compiles, but it doesn’t set the correct text! The Choice. Questionconstructor should call the set. Textmethod of the Questionclass.

Overriding Methods If you are not satisfied with the behavior of an inherited method, you override it by specifying a new implementation in the subclass. An overriding method can extend or replace the functionality of the superclass method. The display method of the Choice. Questionclass needs to: Display the question text. Display the answer choices.

Overriding Methods Problem: Choice. Question's displaymethod can’t access the textvariable of the superclass directly because it is private. Solution: It can call the displaymethod of the superclass, by using the reserved word super public void display() { // Display the question text super. display(); // OK // Display the answer choices. . . } superis a reserved word that forces execution of the superclass method.

section_3/Question. Demo 2. java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import java. util. Scanner; /** This program shows a simple quiz with two choice questions. */ public class Question. Demo 2 { public static void main(String[] args) { Choice. Question first = new Choice. Question(); first. set. Text( "What was the original name of the Java language? "); first. add. Choice( "*7", false); first. add. Choice( "Duke", false); first. add. Choice( "Oak", true); first. add. Choice( "Gosling", false); Choice. Question second = new Choice. Question(); second. set. Text( "In which country was the inventor of Java born? "); second. add. Choice( "Australia", false); second. add. Choice( "Canada", true); second. add. Choice( "Denmark", false); second. add. Choice( "United States" , false); present. Question(first); present. Question(second); } /** Presents a question to the user and checks the response. @param q the question */ public static void present. Question(Choice. Question q) { q. display(); System. out. print( "Your answer: ");

section_3/Choice. Question. java 1 import java. util. Array. List; 2 3 /** 4 A question with multiple choices. 5 */ 6 public class Choice. Question extends Question 7 { 8 private Array. List<String> choices; /** 9 10 Constructs a choice question with no choices. 11 */ public Choice. Question() 12 { 13 choices = new Array. List<String>(); 14 } 15 16 /** 17 18 Adds an answer choice to this question. 19 @param choice the choice to add 20 @param correct true if this is the correct choice, false otherwise 21 */ public void add. Choice(String choice, boolean correct) 22 { 23 24 choices. add(choice); 25 if (correct) { 26 27 // Convert choices. size() to string 28

Program Run: What was the original name of the Java language? 1: *7 2: Duke 3: Oak 4: Gosling Your answer: *7 false In which country was the inventor of Java born? 1: Australia 2: Canada 3: Denmark 4: United States Your answer: 2 true

Syntax 9. 2 Calling a Superclass Method

Common Error: Accidental Overloading: when two methods have the same name but different parameter types. Overriding: when a subclass method provides an implementation of a superclass method whose parameter variables have the same types. When overriding a method, the types of the parameter variables must match exactly.

Common Error: Forgetting to Use super When Invoking Superclass Method Use superwhen extending Employee functionality to Manager class public class Manager {. . . public double get. Salary() { double base. Salary = get. Salary(); // Error: should be super. get. Salary() return base. Salary + bonus; } }

Syntax 9. 3 Constructor with Superclass Initializer

Object: The Cosmic Superclass Every class defined without an explicit extendsclause automatically extend Object: The class Objectis the direct or indirect superclass of every class in Java. Some methods defined in Object: to. String- which yields a string describing the object equals- which compares objects with each other hash. Code- which yields a numerical code for storing the object in a set

Object: The Cosmic Superclass Figure 9 The Object. Class Is the Superclass of Every Java Class

Overriding the t o S t r i n g Method Returns a string representation of the object Useful for debugging: Rectangle box = new Rectangle(5, 10, 20, 30); String s = box. to. String(); // Sets s to "java. awt. Rectangle[x=5, y=10, width=20, height=30]" to. Stringis called whenever you concatenate a string with an object: "box=" + box; // Result: "box=java. awt. Rectangle[x=5, y=10, width=20, height=30]" The compiler can invoke the to. Stringmethod, because it knows that every object has a to. Stringmethod: Every class extends the Objectclass which declares to. String

Overriding the t o S t r i n g Method Object. to. Stringprints class name and the hash code of the object: Bank. Account moms. Savings = new Bank. Account(5000); String s = moms. Savings. to. String(); // Sets s to something like "Bank. Account@d 24606 bf" Override the to. Stringmethod in your classes to yield a string that describes the object’s state. public String to. String() { return "Bank. Account[balance=" + balance + "]"; } This works better: Bank. Account moms. Savings = new Bank. Account(5000); String s = moms. Savings. to. String(); // Sets s to "Bank. Account[balance=5000]"

Overriding the e q u a l s Method equalsmethod checks whether two objects have the same content: if (stamp 1. equals(stamp 2)). . . // Contents are the same ==operator tests whether two references are identical - referring to the same object: if (stamp 1 == stamp 2). . . // Objects are the same

Overriding the e q u a l s Method Figure 10 Two References to Equal Objects Figure 11 Two References to the Same Object

Overriding the e q u a l s Method To implement the equals method for a Stampclass Override the equalsmethod of the Objectclass: public class Stamp { private String color; private int value; . . . public boolean equals(Object other. Object) {. . . } Cannot change parameter type of the equalsmethod - it must be Object Cast the parameter variable to the class Stampinstead: Stamp other = (Stamp) other. Object;

Overriding the e q u a l s Method After casting, you can compare two Stamps public boolean equals(Object other. Object) { Stamp other = (Stamp) other. Object; return color. equals(other. color) && value == other. value; } The equalsmethod can access the instance variables of any Stampobject. The access other. coloris legal.

The i n s t a n c e o f Operator It is legal to store a subclass reference in a superclass variable: Choice. Question cq = new Choice. Question(); Question q = cq; // OK Object obj = cq; // OK Sometimes you need to convert from a superclass reference to a subclass reference. If you know a variable of type Objectactually holds a Questionreference, you can cast Question q = (Question) obj If obj refers to an object of an unrelated type, "class cast" exception is thrown. The instanceofoperator tests whether an object belongs to a particular type. obj instanceof Question Using the instanceofoperator, a safe cast can be programmed as follows: if (obj instanceof Question) { Question q = (Question) obj; }

Polym orphis m Problem: to present both Questionand Choice. Questionwith the same program. We do not need to know the exact type of the question We need to display the question We need to check whether the user supplied the correct answer The Questionsuperclass has methods for displaying and checking. We can simply declare the parameter variable of the present. Question method to have the type Question: public static void present. Question(Question q) { q. display(); System. out. print("Your answer: "); Scanner in = new Scanner(System. in); String response = in. next. Line(); System. out. println(q. check. Answer(response)); }

Polymorphism - continued We can substitute a subclass object whenever a superclass object is expected: Choice. Question second = new Choice. Question(); . . . present. Question(second); // OK to pass a Choice. Question When the present. Questionmethod executes The object references stored in secondand qrefer to the same object The object is of type Choice. Question Figure 7 Variables of Different Types Referring to the Same Object

Polymorphism - continued The variable qknows less than the full story about the object to which it refers Figure 8 A Question Reference Can Refer to an Object of Any Subclass of Question In the same way that vehicles can differ in their method of locomotion, polymorphic objects carry out tasks in different ways.

Polymorphism - continued When the virtual machine calls an instance method It locates the method of the implicit parameter’s class. This is called dynamic method lookup Dynamic method lookup allows us to treat objects of different classes in a uniform way. This feature is called polymorphism. We ask multiple objects to carry out a task, and each object does so in its own way. Polymorphism means “having multiple forms” It allows us to manipulate objects that share a set of tasks, even though the tasks are executed in different ways.

section_4/Question. Demo 3. java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import java. util. Scanner; /** This program shows a simple quiz with two question types. */ public class Question. Demo 3 { public static void main(String[] args) { Question first = new Question(); first. set. Text( "Who was the inventor of Java? "); first. set. Answer( "James Gosling"); Choice. Question second = new Choice. Question(); second. set. Text( "In which country was the inventor of Java born? "); second. add. Choice( "Australia", false); second. add. Choice( "Canada", true); second. add. Choice( "Denmark", false); second. add. Choice( "United States" , false); present. Question(first); present. Question(second); } /** Presents a question to the user and checks the response. @param q the question */ public static void present. Question(Question q) { q. display(); System. out. print( "Your answer: "); Scanner in = new Scanner(System. in); String response = in. next. Line(); System. out. println(q. check. Answer(response));

Program Run: Who was the inventor of Java? Your answer: Bjarne Stroustrup false In which country was the inventor of Java born? 1: Australia 2: Canada 3: Denmark 4: United States Your answer: 2 true

Example class hierarchy Animal Cat Dog Horse

Polymorphism Normally we have this when we create an object: Dog dog = new Dog(); Polymorphism allows us to also do this: Animal pet = new Dog(); The object reference variable can be a super class of the actual object type! (Does NOT work the other way around: Dog is an Animal but Animal is not necessarily a Dog)

Where Polymorphism is Helpful Arrays Array. Lists Passing parameters Returning values from a method
![Polymorphic Array Example Animal[] my. Pets[0] = new my. Pets[1] = new my. Pets[3] Polymorphic Array Example Animal[] my. Pets[0] = new my. Pets[1] = new my. Pets[3]](http://slidetodoc.com/presentation_image/481086379b549826bddfe8faef1eb6ac/image-45.jpg)
Polymorphic Array Example Animal[] my. Pets[0] = new my. Pets[1] = new my. Pets[3] = new Animal[5]; Cat(); You can put any subclass Dog(); of Animal in the Animal array! for (int i = 0; i < my. Pets. length; i++) { my. Pets. feed(); }

Polymorphic Array. List Example Array. List<Animal> my. Pets = new Array. List<Animal>(); Animal a = new Cat(); Animal b = new Cat(); Animal c = new Dog(); my. Pets. add(a); You can put any subclass my. Pets. add(b); of Animal in the Array. List of Animals! my. Pets. add(c); for (Animal p: my. Pets) { p. feed(); }

Polymorphic Arguments public class Vet { public void give. Shot(Animal pet) { pet. make. Noise(); } } public class Pet. Owner { Vet vet = new Vet(); Dog dog = new Dog(); Cat cat = new Cat(); } vet. give. Shot(dog); vet. give. Shot(cat);

Side Effects of Polymorphism Array. List pets = new Array. List(); Dog dog = new Dog(); pets. add(dog); int index = pets. index. Of(dog); Dog dog 1 = pets. get(index); // won’t work Object dog 2 = pets. get(index); dog 2. bark(); // won’t work ((Dog)dog 2). bark(); casting // works because of if (dog 2 instanceof Dog) { ((Dog)dog 2). bark(); } // being careful Dog dog 3 = (Dog) pets. get(index); casting // works because of if (dog 2 instanceof Dog) { Dog dog 4 = (Dog) dog 2; } // being careful
- Slides: 48