1 / 115

Chapter Goals

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. Inheritance:

Download Presentation

Chapter Goals

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 superclassObject and its methods

  2. 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 Vehicle Motorcycle Car Truck SUV Sedan

  3. The classCar inherits from the class Vehicle The Vehicle class is the superclass The Car class is the subclass Figure 2 Inheritance Diagram Inheritance Hierarchies Superclass Subclass

  4. 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) Inheritance Hierarchies Employee -name -Id +getSalary() +getName() SalariedEmployee -weeklySalary +calculateBonus() CommissionEmployee -grossSales -commissionRate +getCommissionRate()

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

  6. 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();

  7. 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. Inheritance Hierarchies

  8. Question • What are candidate attributes and methods of Question class?

  9. Answer Question -text : String -answer : String + setText(String questionText) + setAnswer(String correctResponse) + checkAnswer(String response) + display()

  10. Programming Question • Implement the Question class • 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

  11. 1 /** 2 A question with a text and an answer. 3 */ 4 publicclass 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 @paramquestionText the text of this question 21 */ 22 publicvoidsetText(StringquestionText) 23 { 24 text = questionText; 25 } 26 Answer Question.java Continued

  12. 27 /** 28 Sets the answer for this question. 29 @paramcorrectResponse the answer 30 */ 31 publicvoidsetAnswer(StringcorrectResponse) 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 publicbooleancheckAnswer(String response) 42 { 43 returnresponse.equals(answer); 44 } 45 46 /** 47 Displays this question. 48 */ 49 publicvoid display() 50 { 51 System.out.println(text); 52 } 53 } section_1/Question.java

  13. 1 importjava.util.Scanner; 2 3 /** 4 This program shows a simple quiz with one question. 5 */ 6 publicclass QuestionDemo1 7 { 8 publicstaticvoidmain(String[] args) 9 { 10 Scanner in = newScanner(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 QuestionDemo1.java Continued

  14. Consider classes Manager and Employee. Which should be the superclass and which should be the subclass? Question

  15. 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.

  16. What are the inheritance relationships between classes BankAccount, CheckingAccount, and SavingsAccount? Question

  17. Answer CheckingAccount and SavingsAccount both inherit from the more general class BankAccount.

  18. Consider the method doSomething(Carc). List all vehicle classes from Figure 1 whose objects cannot be passed to this method. Question Vehicle Motorcycle Car Truck SUV Sedan

  19. Answer doSomething(Car c) Vehicle Motorcycle Car Truck SUV Sedan Answer:Vehicle, Truck, Motorcycle

  20. Should a class Quiz inherit from the class Question? Why or why not? Question

  21. Answer It shouldn’t. A quiz isn’t a question; it has questions.

  22. A programmer makes a subclass by modifying another class. E.g. To get a ChoiceQuestion class, implement it as a subclass of Question Implementing Subclasses

  23. 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 superclassobjects!

  24. Figure 4 The ChoiceQuestion Class is a Subclass of the Question Class. Implementing Subclasses • 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;

  25. 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?”);

  26. 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 Implementing Subclasses

  27. How is ChoiceQuestion object different from Question object? Its objects store the various choices for the answer. There is a method for adding answer choices (addChoice method). The display method of the ChoiceQuestion class shows these choices (overriden) so that the respondent can choose one of them. Implementing Subclasses Overridden by subclass

  28. The ChoiceQuestion class needs to spell out the three differences: public class ChoiceQuestionextends Question { // This instance variable is added to the subclass private ArrayList<String> 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. Implementing Subclasses

  29. Syntax 9.1 Subclass Declaration

  30. Inside ChoiceQuestion class implementation it is ok to call publicsuperclass methods as its own: E.g. Inside a ChoiceQuestion class method: setAnswer(“A”); //call superclasssetAnswer 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 ChoiceObjectoverriden implementation Implementing Subclasses A ChoiceQuestion object

  31. 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); } } Implementing Subclasses

  32. addChoice method can not just access the answer variable in the superclass It MUSTuse the setAnswer method Invoke setAnswer on the implicit parameter: setAnswer(choiceString); OR this.setAnswer(choiceString); Implementing Subclasses

  33. 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.

  34. 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

  35. Answer Question.java publicclass Question { private String text; private String answer; public Question(){ text =""; answer =""; } public Question(String text, String answer) { this.text = text this.answer = answer; } publicvoidsetText(String questionText){ text =questionText; } publicvoidsetAnswer(String correctResponse){ answer =correctResponse; } publicbooleancheckAnswer(String response){ returnresponse.equals(answer); } publicvoid display(){ System.out.println(text); } public String getText(){ return text; } }

  36. Answer ChoiceQuestion.java importjava.util.ArrayList; publicclassChoiceQuestionextends Question { // This instance variable is added to the subclass privateArrayList<String> choices; publicChoiceQuestion() { choices =newArrayList<String>(); } // This method is added to the subclass publicvoid addChoice(String choice,boolean correct) { choices.add(choice); if(correct) setAnswer(choice); } }

  37. Answer QuestionDemo.java importjava.util.Scanner; publicclassQuestionDemo { publicstaticvoid 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 =newChoiceQuestion(); chq.setText("Does java use a compiler, interpreter or both?"); chq.addChoice("compiler",false); chq.addChoice("interpreter",false); chq.addChoice("both",true); chq.display(); } }

  38. 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?”;

  39. 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: publicChoiceQuestion() { super(); //Question class should have a matching parameter list to one of the constructors defined in superclass choices =newArrayList<String>(); }

  40. 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. publicChoiceQuestion() { choices =newArrayList<String>(); }

  41. 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) Question

  42. 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) Answer

  43. A subclass has no access to the private instance variables of the superclass: public ChoiceQuestion(StringquestionText) { 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<String> choices; private String text; // Don’t! . . . } Common Error: Replicating Instance Variables from the Superclass

  44. 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. Common Error: Replicating Instance Variables from the Superclass

  45. 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! Overriding Methods

  46. Programming Question • Modify ChoiceQuestion class so that it override the display method in question class

  47. 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. Answer

  48. Syntax 9.2 Calling a Superclass Method

  49. 1 importjava.util.ArrayList; 2 3 /** 4 A question with multiple choices. 5 */ 6 publicclassChoiceQuestionextends Question 7 { 8 privateArrayList<String> choices; 9 10 /** 11 Constructs a choice question with no choices. 12 */ 13 publicChoiceQuestion() 14 { 15 choices = newArrayList<String>(); 16 } 17 Answer ChoiceQuestion.java Continued

More Related