Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 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 Object and its methods

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 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 Vehicle Motorcycle Car Truck Sedan SUV

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Inheritance Hierarchies  The class Car inherits from the class Vehicle  The Vehicle class is the superclass  The Car class is the subclass Figure 2 Inheritance Diagram Superclass Subclass

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Inheritance Hierarchies  Inheritance lets you can reuse code instead of duplicating it.  A class can be defined as a "subclass" of another class. The subclass inherits all data attributes of its superclass The subclass inherits all methods of its superclass The subclass can: Add new functionality Use inherited functionality Override inherited functionality (modify) Employee -name -Id +getSalary() +getName() SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Employee -name -Id +getSalary() +getName() +setID(id) SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate() parent/supercalss of SalariedEmployee class and CommissionEmployee Subclasses of Employee Inherit name and id attributes from Employee Inherit methods getSaray and getName from Employee Additional attributes Additional methods Inherited + overridden by subclasses Inherited and used as it is by subclasses SalariedEmployee salEmp = new SalariedEmployee(); salEmp.calculateBonus(); salEmp.setID(12345); //change ID attribute salEmp.getCommissionRate();

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7  The substitution principle: You can always use a subclass object when a superclass object is expected. A method that processes Vehicle objects can handle any kind of vehicle Person Employee SalariedEmployee CommissionEmployee Employee emp = new SalariedEmployee(); Person person = new CommissionEmployee();

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 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 Question class.

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Question  What are candidate attributes and methods of Question class?

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Answer Question -text : String -answer : String + setText(String questionText) + setAnswer(String correctResponse) + checkAnswer(String response) + display()

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Programming Question 1.Implement the Question class 2.Implementer the tester class QuestionDemo1 with following code in main method: Question -text : String -answer : String + setText(String questionText) + setAnswer(String correctResponse) + checkAnswer(String response) + display() Scanner in = new Scanner(System.in); Question q = new Question(); q.setText("Who was the inventor of Java?"); q.setAnswer("James Gosling"); q.display(); System.out.print("Your answer: "); String response = in.nextLine(); System.out.println(q.checkAnswer(response)); Program Run: Who was the inventor of Java? Your answer: James Gosling true

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Answer 1 /** 2 A question with a text and an answer. 3 */ 4 public class Question 5 { 6 private String text; 7 private String answer; 8 9 /** 10 Constructs a question with empty question and answer. 11 */ 12 public Question() 13 { 14 text = ""; 15 answer = ""; 16 } 17 18 /** 19 Sets the question text. 20 @param questionText the text of this question 21 */ 22 public void setText(String questionText) 23 { 24 text = questionText; 25 } 26 Continued Question.java

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13 section_1/Question.javaQuestion.java 27 /** 28 Sets the answer for this question. 29 @param correctResponse the answer 30 */ 31 public void setAnswer(String correctResponse) 32 { 33 answer = correctResponse; 34 } 35 36 /** 37 Checks a given response for correctness. 38 @param response the response to check 39 @return true if the response was correct, false otherwise 40 */ 41 public boolean checkAnswer(String response) 42 { 43 return response.equals(answer); 44 } 45 46 /** 47 Displays this question. 48 */ 49 public void display() 50 { 51 System.out.println(text); 52 } 53 }

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 1 import java.util.Scanner; 2 3 /** 4 This program shows a simple quiz with one question. 5 */ 6 public class QuestionDemo1 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 12 Question q = new Question(); 13 q.setText("Who was the inventor of Java?"); 14 q.setAnswer("James Gosling"); 15 16 q.display(); 17 System.out.print("Your answer: "); 18 String response = in.nextLine(); 19 System.out.println(q.checkAnswer(response)); 20 } 21 } 22 Continued QuestionDemo1.java

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Question Consider classes Manager and Employee. Which should be the superclass and which should be the subclass?

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Answer Because every manager is an employee but not the other way around, the Manager class is more specialized. It is the subclass, and Employee is the superclass.

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Question What are the inheritance relationships between classes BankAccount, CheckingAccount, and SavingsAccount?

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 Answer CheckingAccount and SavingsAccount both inherit from the more general class BankAccount.

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Question Consider the method doSomething(Car c). List all vehicle classes from Figure 1 whose objects cannot be passed to this method. Vehicle Motorcycle Car Truck Sedan SUV

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Answer Answer: Vehicle, Truck, Motorcycle doSomething(Car c) Vehicle Motorcycle Car Truck Sedan SUV

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Question Should a class Quiz inherit from the class Question? Why or why not?

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Answer It shouldn’t. A quiz isn’t a question; it has questions.

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Implementing Subclasses  A programmer makes a subclass by modifying another class.  E.g. To get a ChoiceQuestion class, implement it as a subclass of Question

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Implementing Subclasses  variable declaration in subclasses: Subclass objects automatically have the instance variables that are declared in the superclass. When implementing subclass, only declare instance variables that are not part of the superclass objects!

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Implementing Subclasses Figure 4 The ChoiceQuestion Class is a Subclass of the Question Class. Inside ChoiceQuestion methods, the private instance variables of the superclass are inaccessible. E.g. Inside ChoiceQuestion methods: text=“Does java use a compiler, interpreter or both?”; return answer;

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Implementing Subclasses  Instead, ChoiceQuestion methods must use the public interface of the Question class to access its private data. E.g. Inside ChoiceQuestion methods: setText(“Does java use a compiler, interpreter or both?”);

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Implementing Subclasses  Method declaration in subclasses: The subclass inherits all public methods from the superclass. You declare any methods that are new to the subclass. You override (i.e. change) the implementation of inherited methods if the inherited behavior is not appropriate. Override a method: – supply a new implementation for an inherited method

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Implementing Subclasses  How is ChoiceQuestion object different from Question object? 1.Its objects store the various choices for the answer. 2.There is a method for adding answer choices (addChoice method). 3.The display method of the ChoiceQuestion class shows these choices (overriden) so that the respondent can choose one of them. Overridden by subclass

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Implementing Subclasses  The ChoiceQuestion class needs to spell out the three differences: public class ChoiceQuestion extends Question { // This instance variable is added to the subclass private ArrayList choices; // This method is added to the subclass public void addChoice(String choice, boolean correct) {... } // This method overrides a method from the superclass public void display() {... } }  The extends reserved word indicates that a class inherits from a superclass.

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Syntax 9.1 Subclass Declaration

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Implementing Subclasses  Inside ChoiceQuestion class implementation it is ok to call public superclass methods as its own: E.g. Inside a ChoiceQuestion class method: setAnswer(“A”); //call superclass setAnswer method  An outside classes can call the inherited methods on a subclass object: choiceQuestion.setAnswer("2");  If an outside classes call overridden method display method on a ChoiceQuestion object overridden behavior is executed: choiceQuestion.display()//call ChoiceObject overriden implementation A ChoiceQuestion object

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 Implementing Subclasses  Adding a new method: addChoice public void addChoice(String choice, boolean correct) { choices.add(choice); if (correct) { // Convert choices.size() to string String choiceString = "" + choices.size(); setAnswer(choiceString); } }

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Implementing Subclasses  addChoice method can not just access the answer variable in the superclass  It MUST use the setAnswer method  Invoke setAnswer on the implicit parameter: setAnswer(choiceString); OR this.setAnswer(choiceString);

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Class Extension  A subclass inherits the variables and methods of its superclass, with the exception of constructors, private variables, and private methods.  Inherited variables and methods behave as though they were declared in the subclass.  The subclass may define additional variables and methods that were not present in the superclass.  A superclass can be any previously existing class, including a class in the Java API.

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Programming Question  Implement the ChoiceQuestion class. Declare additional variables and implement addChoice method  Update QuestionDemo1 to create a ChoiceQuestion object and add following: Question: Does java use a compiler, interpreter or both? 3 Choices: compiler, interpreter, both  Display the question Overridden by subclass

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Answer public class Question { private String text; private String answer; public Question() { text = ""; answer = ""; } public Question(String text, String answer) { this.text = text this.answer = answer; } public void setText(String questionText) { text = questionText; } public void setAnswer(String correctResponse){ answer = correctResponse; } public boolean checkAnswer(String response){ return response.equals(answer); } public void display() { System.out.println(text); } public String getText() { return text; } Question.java

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Answer import java.util.ArrayList; public class ChoiceQuestion extends Question { // This instance variable is added to the subclass private ArrayList choices; public ChoiceQuestion() { choices = new ArrayList (); } // This method is added to the subclass public void addChoice(String choice, boolean correct) { choices.add(choice); if(correct) setAnswer(choice); } } ChoiceQuestion.java

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Answer import java.util.Scanner; public class QuestionDemo { public static void main(String[] args) { Scanner in = new Scanner(System.in); Question q = new Question(); q.setText("Who was the inventor of Java?"); q.setAnswer("James Gosling"); q.display(); System.out.print("Your answer: "); String response = in.nextLine(); System.out.println(q.checkAnswer(response)); ChoiceQuestion chq = new ChoiceQuestion(); chq.setText("Does java use a compiler, interpreter or both?"); chq.addChoice("compiler", false); chq.addChoice("interpreter", false); chq.addChoice("both", true); chq.display(); } QuestionDemo.java

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Writing Subclass Constructors  A subclass doesn’t inherit constructors from its superclass  Therefore subclass needs to define its own constructors.  How to initialize superclass variables in subclass constructor? Remember, superclass variables are likely to be private!. E.g. in ChoiceQuestion methods: text=“Does java use a compiler, interpreter or both?”;

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Writing Subclass Constructors  Solution: Call superclass constructor within subclass constructor Use super keyword Must be the first statement in the subclass constructor Have additional statements to initialize variables declared in subclass E.g. ChoiceQuestion constructor: public ChoiceQuestion() { super(); //Question class should have a matching parameter list to one of the constructors defined in superclass choices = new ArrayList (); }

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Writing Subclass Constructors  What if subclass constructor fails to call super? Then the compiler will automatically insert super() at the beginning of the constructor.  What if a subclass has no constructors at all? Then the compiler will create a no argument constructor in subclass that contains super(). This will be the only statement in constructor. public ChoiceQuestion() { choices = new ArrayList (); }

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Question Suppose q is an object of the class Question and cq an object of the class ChoiceQuestion. Which of the following calls are legal? a. q.setAnswer(response) b. cq.setAnswer(response) c. q.addChoice(choice, true) d. cq.addChoice(choice, true)

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Answer Answer: a, b, d Suppose q is an object of the class Question and cq an object of the class ChoiceQuestion. Which of the following calls are legal? a. q.setAnswer(response) b. cq.setAnswer(response) c. q.addChoice(choice, true) d. cq.addChoice(choice, true)

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Common Error: Replicating Instance Variables from the Superclass  A subclass has no access to the private instance variables of the superclass: public ChoiceQuestion(String questionText) { text = questionText; // Error—tries to access // private superclass variable }  Beginner's error: “solve” this problem by adding another instance variable with same name public class ChoiceQuestion extends Question { private ArrayList choices; private String text; // Don’t!... }

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Common Error: Replicating Instance Variables from the Superclass  The constructor compiles, but it doesn’t set the correct text!  Correct way: The ChoiceQuestion constructor should call the setText method of the Question class.

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Overriding Methods  If you are not satisfied with the behavior of an inherited method, Override it by specifying a new implementation in the subclass.  An overriding method can extend or replace the functionality of the superclass method.  E.g. The display method of the ChoiceQuestion class needs to: Display the question text. Display the answer choices. So, superclass implementation of display is not sufficient!

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Programming Question  Modify ChoiceQuestion class so that it override the display method in question class

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Answer  Problem: ChoiceQuestion's display method can’t access the text variable of the superclass directly because it is private.  Solution: It can call the display method of the superclass, by using the reserved word super public void display() { // Display the question text super.display(); // OK // Display the answer choices... } super is a reserved word that forces execution of the superclass method.

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Syntax 9.2 Calling a Superclass Method

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 Answer 1 import java.util.ArrayList; 2 3 /** 4 A question with multiple choices. 5 */ 6 public class ChoiceQuestion extends Question 7 { 8 private ArrayList choices; 9 10 /** 11 Constructs a choice question with no choices. 12 */ 13 public ChoiceQuestion() 14 { 15 choices = new ArrayList (); 16 } 17 Continued ChoiceQuestion.java

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 18 /** 19 Adds an answer choice to this question. 20 @param choice the choice to add 21 @param correct true if this is the correct choice, false otherwise 22 */ 23 public void addChoice(String choice, boolean correct) 24 { 25 choices.add(choice); 26 if (correct) 27 { 28 // Convert choices.size() to string 29 String choiceString = "" + choices.size(); 30 setAnswer(choiceString); 31 } 32 } 33 34 public void display() 35 { 36 // Display the question text 37 super.display(); 38 // Display the answer choices 39 for (int i = 0; i < choices.size(); i++) 40 { 41 int choiceNumber = i + 1; 42 System.out.println(choiceNumber + ": " + choices.get(i)); 43 } 44 } 45 } 46 Continued

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 1 import java.util.Scanner; 2 3 /** 4 This program shows a simple quiz with two choice questions. 5 */ 6 public class QuestionDemo2 7 { 8 public static void main(String[] args) 9 { 10 ChoiceQuestion first = new ChoiceQuestion(); 11 first.setText("What was the original name of the Java language?"); 12 first.addChoice("*7", false); 13 first.addChoice("Duke", false); 14 first.addChoice("Oak", true); 15 first.addChoice("Gosling", false); 16 17 ChoiceQuestion second = new ChoiceQuestion(); 18 second.setText("In which country was the inventor of Java born?"); 19 second.addChoice("Australia", false); 20 second.addChoice("Canada", true); 21 second.addChoice("Denmark", false); 22 second.addChoice("United States", false); 23 24 presentQuestion(first); 25 presentQuestion(second); 26 } 27 Continued QuestionDemo2.java

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 28 /** 29 Presents a question to the user and checks the response. 30 @param q the question 31 */ 32 public static void presentQuestion(ChoiceQuestion q) 33 { 34 q.display(); 35 System.out.print("Your answer: "); 36 Scanner in = new Scanner(System.in); 37 String response = in.nextLine(); 38 System.out.println(q.checkAnswer(response)); 39 } 40 } 41 Continued

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54 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

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55 Question Answer: The type of the this reference is ChoiceQuestion. Therefore, the display method of ChoiceQuestion is selected, and the method calls itself. What is wrong with the following implementation of the display method? public class ChoiceQuestion {... public void display() { this.display(); for (int i = 0; i < choices.size(); i++) { int choiceNumber = i + 1; System.out.println(choiceNumber + ": " + choices.get(i)); }

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Question Answer: Because there is no ambiguity. The subclass doesn’t have a setAnswer method. Look again at the implementation of the addChoice method that calls the setAnswer method of the superclass. Why don’t you need to call super.setAnswer?

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Polymorphism  Polymorphism: Ability of an object to take on many forms.  Polymorphism in OOP: The most common use: A parent class reference is used to refer to a child class object.

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Polymorphism  Overloading: when two methods in the same class have the same name but different parameter types. Called static polymorphism. Can be determined at compile time

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59  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. Called dynamic polymorphism (most popular form of polymorphism) Determined at run time

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Polymorphism  E.g. 3 classes in inheritance hierarchy public class Person{} public class Student extends Person{} public class GraduateStudent extends Student{}  All following statements are valid (type of reference is a superclass of type of object): Person p = new Student(); Person p = new GraduateStudent(); Student s = new GraduatrStudent(); Object o = new GraduatrStudent();  What does a call to p.display() print?

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 Polymorphism  Answer: It depends. You cannot find the version of display being called at compile time (static binding is not possible). Instead, type of p will have to be tested during program execution/runtime (dynamic binding).  E.g. If different objects are assigned to p during execution, different versions of display may be called: p = new Student(); p.display(); // Calls display method in Student class p = new GraduateStudent(); p.display(); // Calls display method in GraduateStudent class

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62 Polymorphism  E.g. Question and ChoiceQuestion class hierarchy: Display method can be dynamically bound to a ChoiceQuestion object: Question q = new ChoiceQuestion();  Notice that we do not need to know the exact type of the question to execute display method: public static void presentQuestion(Question q) { q.display(); System.out.print("Your answer: "); Scanner in = new Scanner(System.in); String response = in.nextLine(); System.out.println(q.checkAnswer(response)); }  We can substitute a subclass object whenever a superclass object is expected: ChoiceQuestion second = new ChoiceQuestion(); presentQuestion(second); // OK to pass a ChoiceQuestion

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Polymorphism  When the presentQuestion method executes – The object references stored in second and q refer to the same object The object is of type ChoiceQuestion Figure 7 Variables of Different Types Referring to the Same Object

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 section_4/QuestionDemo3.javaQuestionDemo3.java 1 import java.util.Scanner; 2 3 /** 4 This program shows a simple quiz with two question types. 5 */ 6 public class QuestionDemo3 7 { 8 public static void main(String[] args) 9 { 10 Question first = new Question(); 11 first.setText("Who was the inventor of Java?"); 12 first.setAnswer("James Gosling"); 13 14 ChoiceQuestion second = new ChoiceQuestion(); 15 second.setText("In which country was the inventor of Java born?"); 16 second.addChoice("Australia", false); 17 second.addChoice("Canada", true); 18 second.addChoice("Denmark", false); 19 second.addChoice("United States", false); 20 21 presentQuestion(first); 22 presentQuestion(second); 23 } 24 Continued

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 section_4/QuestionDemo3.javaQuestionDemo3.java 25 /** 26 Presents a question to the user and checks the response. 27 @param q the question 28 */ 29 public static void presentQuestion(Question q) 30 { 31 q.display(); 32 System.out.print("Your answer: "); 33 Scanner in = new Scanner(System.in); 34 String response = in.nextLine(); 35 System.out.println(q.checkAnswer(response)); 36 } 37 } 38 Continued

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 section_4/QuestionDemo3.javaQuestionDemo3.java 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

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Question Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java? a. BankAccount account = new SavingsAccount(); b. SavingsAccount account2 = new BankAccount(); c. BankAccount account = null; SavingsAccount account2 = account;

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Answer Answer: a only. Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java? a. BankAccount account = new SavingsAccount(); b. SavingsAccount account2 = new BankAccount(); c. BankAccount account = null; SavingsAccount account2 = account;

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Question If account is a variable of type BankAccount that holds a non-null reference, what do you know about the object to which account refers?

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 Answer It belongs to the class BankAccount or one of its subclasses.

71 Copyright © 2014 by John Wiley & Sons. All rights reserved.71 Object: The Cosmic Superclass  Every class defined without an explicit extends clause automatically extend Object  The class Object is the direct or indirect superclass of every class in Java.  Some methods defined in Object: toString - which yields a string describing the object equals - which compares objects with each other hashCode - which yields a numerical code for storing the object in a set getClass – return the runtime class of this object

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72 Programming Question  Insert the following code in QuestionDemo3.java and run: ChoiceQuestion chq = new ChoiceQuestion(); chq.setText("Does java use a compiler, interpreter or both?"); chq.addChoice("compiler", false); chq.addChoice("interpreter", false); chq.addChoice("both", true); Question q = chq; System.out.println(q.getClass());

73 Copyright © 2014 by John Wiley & Sons. All rights reserved.73  Returns:

74 Copyright © 2014 by John Wiley & Sons. All rights reserved.74 Object: The Cosmic Superclass Figure 9 The Object Class Is the Superclass of Every Java Class

75 Copyright © 2014 by John Wiley & Sons. All rights reserved.75 Overriding the toString Method  Returns a string representation of the object  Useful for debugging: Rectangle box = new Rectangle(5, 10, 20, 30); String s = box.toString(); // Sets s to "java.awt.Rectangle[x=5,y=10,width=20,height=30]"  toString is 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 toString method, because it knows that every object has a toString method: Every class extends the Object class which declares toString

76 Copyright © 2014 by John Wiley & Sons. All rights reserved.76 Overriding the toString Method  Object.toString prints class name and the hash code of the object: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to something like "BankAccount@d24606bf"  Override the toString method in your classes to yield a string that describes the object’s state. public String toString() { return "BankAccount[balance=" + balance + "]”; }  This works better: BankAccount momsSavings = new BankAccount(5000); String s = momsSavings.toString(); // Sets s to "BankAccount[balance=5000]"

77 Copyright © 2014 by John Wiley & Sons. All rights reserved.77 Overriding the equals Method  equals method checks whether two objects have the same content: if (stamp1.equals(stamp2))... // Contents are the same  == operator tests whether two references are identical - referring to the same object: if (stamp1 == stamp2)... // Objects are the same

78 Copyright © 2014 by John Wiley & Sons. All rights reserved.78 Overriding the equals Method Figure 10 Two References to Equal Objects

79 Copyright © 2014 by John Wiley & Sons. All rights reserved.79 Overriding the equals Method Figure 11 Two References to the Same Object

80 Copyright © 2014 by John Wiley & Sons. All rights reserved.80 Overriding the equals Method  To implement the equals method for a Stamp class - Override the equals method of the Object class: public class Stamp { private String color; private int value... public boolean equals(Object otherObject) {... } }  Cannot change parameter type of the equals method - it must be Object  Cast the parameter variable to the class Stamp instead: Stamp other = (Stamp) otherObject;

81 Copyright © 2014 by John Wiley & Sons. All rights reserved.81 Overriding the equals Method  After casting, you can compare two Stamps public boolean equals(Object otherObject) { Stamp other = (Stamp) otherObject; return color.equals(other.color) && value == other.value; }  The equals method can access the instance variables of any Stamp object.  The access other.color is legal.

82 Copyright © 2014 by John Wiley & Sons. All rights reserved.82 Programming Question  Modify your Rectangle.java class so you override the equals method and toString method. equals method should return true only if x,y,width and height matches to rectangle in parameter. To string method should print the x,y,width and height parameters of object Sample output:

83 Copyright © 2014 by John Wiley & Sons. All rights reserved.83 Answer public class Rectangle { int x, y, width, height; public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } /** * overriden equals method * */ public boolean equals(Object object) { Rectangle r = (Rectangle)object; if(x==r.x && y==r.y && width==r.width && height==r.height) return true; return false; } public String toString() { return "Rectangle [x:"+x+" y:"+y+" width:"+width+" height:"+height+"]"; } public static void main(String args[]) { Rectangle r1 = new Rectangle(10,20,50,50); Rectangle r2 = new Rectangle(10,20,50,50); Rectangle r3 = new Rectangle(10,50,50,50); System.out.println("r1= "+r1); System.out.println("r2= "+r2); System.out.println("r3= "+r3); System.out.println("r1.equals(r2)"+r1.equals(r2)); System.out.println("r1.equals(r3)"+r1.equals(r3)); }

84 Copyright © 2014 by John Wiley & Sons. All rights reserved.84 The instanceof Operator  It is legal to store a subclass reference in a superclass variable: ChoiceQuestion cq = new ChoiceQuestion(); 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 Object actually holds a Question reference, you can cast Question q = (Question) obj;  If obj refers to an object of an unrelated type, “class cast” exception is thrown.

85 Copyright © 2014 by John Wiley & Sons. All rights reserved.85 The instanceof Operator  The instanceof operator tests whether an object belongs to a particular type. obj instanceof Question  Using the instanceof operator, a safe cast can be programmed as follows: if (obj instanceof Question) { Question q = (Question) obj; }

86 Copyright © 2014 by John Wiley & Sons. All rights reserved.86 Question Why does the call System.out.println(System.out); produce a result such as java.io.PrintStream@7a84e4?

87 Copyright © 2014 by John Wiley & Sons. All rights reserved.87 Answer Answer: Because the implementor of the PrintStream class did not supply a toString method.

88 Copyright © 2014 by John Wiley & Sons. All rights reserved.88 Question Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Hello"; System.out.println(obj.length());

89 Copyright © 2014 by John Wiley & Sons. All rights reserved.89 Answer Answer: The second line will not compile. The class Object does not have a method length.

90 Copyright © 2014 by John Wiley & Sons. All rights reserved.90 Question Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Who was the inventor of Java?”; Question q = (Question) obj; q.display();

91 Copyright © 2014 by John Wiley & Sons. All rights reserved.91 Answer Answer: The code will compile, but the second line will throw a class cast exception because Question is not a superclass of String.

92 Copyright © 2014 by John Wiley & Sons. All rights reserved.92 Question Assuming that x is an object reference, what is the value of x instanceof Object?

93 Copyright © 2014 by John Wiley & Sons. All rights reserved.93 Answer Answer: The value is false if x is null and true otherwise. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

94 Copyright © 2014 by John Wiley & Sons. All rights reserved.94 When Not to Use Inheritance  Inheritance is appropriate when: the new class “is a” particular case of the old class : The subclass must have every property of the superclass. E.g. – A Car is a Vehicle. – A SavingsAccount is an Account.  Inheritance is inappropriate when: the words “is a” don’t fit. E.g. it wouldn’t make sense to say that a SavingsAccount is a Vehicle.

95 Copyright © 2014 by John Wiley & Sons. All rights reserved.95 Abstract Classes  When you extend an existing class, you have the choice whether or not to override the methods of the superclass.  Sometimes, it is desirable to force programmers to override a method.  That happens when there is no good default for the superclass, and only the subclass programmer can know how to implement the method properly.

96 Copyright © 2014 by John Wiley & Sons. All rights reserved.96 Abstract Classes  E.g. Suppose we decides that every account type must have some monthly fees. Therefore, a deductFees method should be added to the BankAccount class:  But what should the method do? We could have the method do nothing. But then a programmer implementing a new subclass might simply forget to implement the deductFees method: new account would inherit the do-nothing method of the superclass.  There is a better way: declare the deductFees method as an abstract method

97 Copyright © 2014 by John Wiley & Sons. All rights reserved.97 Abstract Classes  An abstract method has no implementation.  This forces the implementers of subclasses to specify concrete implementations of this method.  You cannot construct objects of classes with abstract methods.  A class for which you cannot create objects is called an abstract class.  A class for which you can create objects is sometimes called a concrete class.

98 Copyright © 2014 by John Wiley & Sons. All rights reserved.98 Abstract Classes  In Java, you must declare all abstract classes with the reserved word abstract:  Which classes must be declared abstract? 1.A class that declares an abstract method 2.A class that inherits an abstract method without overriding it 3.Optionally, if you want, declare classes with no abstract methods as abstract. Doing so prevents programmers from creating instances of that class but allows them to create their own subclasses.

99 Copyright © 2014 by John Wiley & Sons. All rights reserved.99 Abstract Classes  You CANNOT construct an object of an abstract class  you can still have a variable whose type is an abstract class. Actual object to which it refers must be an instance of a concrete subclass

100 Copyright © 2014 by John Wiley & Sons. All rights reserved.100 Abstract Classes  Why use abstract classes? To force programmers to create subclasses. By specifying certain methods as abstract you avoid the trouble of coming up with useless default methods that others might inherit by accident.  How do Abstract classes differ from interfaces? Unlike interfaces, abstract classes can have: instance variables, concrete methods and constructors.

101 Copyright © 2014 by John Wiley & Sons. All rights reserved.101 Programming Question  Implement the classes Shape (abstract) and Point class. Class diagram is shown below:  Add a main method to Point class to create a point and print it.  A sample run is shown below:

102 Copyright © 2014 by John Wiley & Sons. All rights reserved.102 Answer import java.awt.Color; abstract class Shape { public Color color; public Shape(Color color) { this.color = color; } public void setColor(Color c) { color = c; } public Color getColor() { return color; } abstract public double area(); } Shape.java import java.awt.Color; public class Point extends Shape { int x, y; public Point(int x, int y, Color color) { super(color); //or setColor(color); this.x = 0; this.y = 0; } public double area() { return 0; } public double perimeter() { return 0; } public String toString() { return "point: x:" + x + " y:" + y+ " color:"+color; } public static void main(String args[]) { Point p = new Point(100,100, Color.BLACK); System.out.println(p); } Point.java

103 Copyright © 2014 by John Wiley & Sons. All rights reserved.103 Final Methods and Classes  Occasionally, you may want to prevent other programmers from creating subclasses or from overriding certain methods. Opposite of abstract methods  In these situations, you use the final reserved word  E.g. String class in Java library is final: i.e. nobody can extend (create subclasses of) the String class The String class is meant to be immutable string objects can’t be modified by any of their methods.

104 Copyright © 2014 by John Wiley & Sons. All rights reserved.104  You can also declare individual methods as final:  All extending subclasses cannot override the checkPassword method with another method that simply returns true. Class is not final

105 Copyright © 2014 by John Wiley & Sons. All rights reserved.105 Common Error  Overriding Methods to Be Less Accessible  If a superclass declares a method to be publicly accessible, you cannot override it to be more private in a subclass.  E.g. superclass: BankAccount  E.g subclass: CheckingAccount The compiler does not allow this

106 Copyright © 2014 by John Wiley & Sons. All rights reserved.106 Enumeration Types  In many programs, you use variables that can hold one of a finite number of values: E.g in TaxReturn class, status variable: Only could hold one of the values SINGLE or MARRIED. We arbitrarily declared SINGLE as the number 1 and MARRIED as 2.  If, due to some programming error, the status variable is set to another integer value (such as –1, 0, or 3), then the programming logic may produce invalid results.  In a simple program, this is not really a problem.  But as programs grow over time, and more cases are added (such as the “married filing separately” and “head of household” categories), errors can slip in.

107 Copyright © 2014 by John Wiley & Sons. All rights reserved.107  Java version 5.0 introduces a remedy: enumeration types.  An enumeration type has a finite set of values  E.g.  You can have any number of values, but you must include them all in the enum declaration.  You can declare variables of the enumeration type:  Use the == operator to compare enumeration values:

108 Copyright © 2014 by John Wiley & Sons. All rights reserved.108  It is common to nest an enum declaration inside a class:  E.g.  To access the enumeration outside the class in which it is declared, use the class name as a prefix:

109 Copyright © 2014 by John Wiley & Sons. All rights reserved.109

110 Copyright © 2014 by John Wiley & Sons. All rights reserved.110  An enumeration type variable can be null.  E.g. the status variable in the previous example can actually have three values: SINGLE, MARRIED, and null.

111 Copyright © 2014 by John Wiley & Sons. All rights reserved.111 Programming Question  Declare a new class FilingStatus.java with folliwing code: public enum FilingStatus{SINGLE, MARRIED}  Modify the TaxReturn class to do the following: Declare getTax() method final Modify class to use FilingStatus for status.  Original TaxReturn class can be downloaded from herehere

112 Copyright © 2014 by John Wiley & Sons. All rights reserved.112 Answer public enum FilingStatus{SINGLE, MARRIED} FilingStatus.java

113 Copyright © 2014 by John Wiley & Sons. All rights reserved.113 1 import java.util.Scanner; 2 /** 3 A tax return of a taxpayer in 2008. 4 */ 5 public class TaxReturn 6 { 7 private static final double RATE1 = 0.10; 8 private static final double RATE2 = 0.25; 9 private static final double RATE1_SINGLE_LIMIT = 32000; 10 private static final double RATE1_MARRIED_LIMIT = 64000; 11 12 private double income; 13 private FilingStatus status; 14 15 /** 16 Constructs a TaxReturn object for a given income and 17 marital status. 18 @param anIncome the taxpayer income 19 @param aStatus either SINGLE or MARRIED 20 */ 21 public TaxReturn(double anIncome, FilingStatus aStatus) 22 { 23 income = anIncome; 24 status = aStatus; 25 } 26 TaxReturn.java CONTINUED..

114 Copyright © 2014 by John Wiley & Sons. All rights reserved.114 27 public final double getTax() 28 { 29 double tax1 = 0; 30 double tax2 = 0; 31 32 if (status == FilingStatus.SINGLE) 33 { 34 if (income <= RATE1_SINGLE_LIMIT) 35 { 36 tax1 = RATE1 * income; 37 } 38 else 39 { 40 tax1 = RATE1 * RATE1_SINGLE_LIMIT; 41 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); 42 } 43 } 44 else 45 { 46 if (income <= RATE1_MARRIED_LIMIT) 47 { 48 tax1 = RATE1 * income; 49 } 50 else 51 { 52 tax1 = RATE1 * RATE1_MARRIED_LIMIT; 53 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); 54 } 55 } 56 57 return tax1 + tax2; 58 }

115 Copyright © 2014 by John Wiley & Sons. All rights reserved.115 59 60 public static void main(String[] args) 61 { 62 Scanner in = new Scanner(System.in); 63 64 System.out.print("Please enter your income: "); 65 double income = in.nextDouble(); 66 67 System.out.print("Are you married? (Y/N) "); 68 String input = in.next(); 69 FilingStatus status; 70 if (input.equals("Y")) 71 { 72 status = FilingStatus.MARRIED; 73 } 74 else 75 { 76 status = FilingStatus.SINGLE; 77 } 78 79 TaxReturn aTaxReturn = new TaxReturn(income, status); 80 81 System.out.println("Tax: “ + aTaxReturn.getTax()); 83 } 84} CONTINUED..


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance."

Similar presentations


Ads by Google