SlideShare a Scribd company logo
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 9 - Inheritance
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
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
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
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 Car object in
algorithms that manipulate Vehicle objects
 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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
section_1/Question.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
section_1/Question.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 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
section_1/QuestionDemo1.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
section_1/QuestionDemo1.java
Program Run:
Who was the inventor of Java?
Your answer: James Gosling
true
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Self Check 9.1
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.
Consider classes Manager and Employee. Which should be
the superclass and which should be the subclass?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Self Check 9.2
Answer: CheckingAccount and SavingsAccount both
inherit from the more general class BankAccount.
What are the inheritance relationships between classes
BankAccount, CheckingAccount, and SavingsAccount?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Self Check 9.3
Answer: The classes Frame, Window, and Component in
the java.awt package, and the class Object in the
java.lang package.
What are all the superclasses of the JFrame class? Consult
the Java API documentation or Appendix D.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Self Check 9.4
Answer: Vehicle, Truck, Motorcycle
Consider the method doSomething(Car c). List all vehicle
classes from Figure 1 whose objects cannot be passed to
this method.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Self Check 9.5
Answer: It shouldn’t. A quiz isn’t a question; it has
questions.
Should a class Quiz inherit from the class Question? Why or
why not?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
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 ChoiceQuestion class, 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
Implementing Subclasses
 A subclass inherits all methods that it does not override.
Figure 4 The ChoiceQuestion Class is a Subclass of the Question
Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Implementing Subclasses
A ChoiceQuestion object differs from a Question object 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 ChoiceQuestion class shows these
choices so that the respondent can choose one of them.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
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<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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Implementing Subclasses
 UML of ChoiceQuestion and Question
Figure 5 The ChoiceQuestion Class Adds an Instance Variable
and a Method, and Overrides a Method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Syntax 9.1 Subclass Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Implementing Subclasses
 A ChoiceQuestion object
 You can call the inherited methods on a subclass object:
choiceQuestion.setAnswer("2");
 The private instance variables of the superclass are
inaccessible.
 The ChoiceQuestion methods cannot directly access the
instance variable answer.
 ChoiceQuestion methods must use the public interface of the
Question class to access its private data.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
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);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
Self Check 9.6
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)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Self Check 9.7
Suppose the class Employee is declared as follows:
public class Employee
{
private String name;
private double baseSalary;
public void setName(String newName) { . . . }
public void setBaseSalary(double newSalary) { . . . }
public String getName() { . . . }
public double getSalary() { . . . }
}
Declare a class Manager that inherits from the class Employee
and adds an instance variable bonus for storing a salary bonus.
Omit constructors and methods.
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Self Check 9.7
Answer:
public class Manager extends Employee
{
private double bonus;
// Constructors and methods omitted
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Self Check 9.8
Answer: name, baseSalary, and bonus
Which instance variables does the Manager class from Self Check
7 have?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Self Check 9.9
Answer:
public class Manager extends Employee
{
. . .
public double getSalary() {
. . .
}
}
In the Manager class, provide the method header (but not the
implementation) for a method that overrides the getSalary
method from the class Employee.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 31
Self Check 9.10
Answer: getName, setName, setBaseSalary
Which methods does the Manager class from Self Check 9
inherit?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 32
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
 Error!
public class ChoiceQuestion extends Question
{
private ArrayList<String> choices;
private String text; // Don’t!
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 33
Common Error: Replicating Instance
Variables from the Superclass
 The constructor compiles, but it doesn’t set the correct text!
 The ChoiceQuestion constructor should call the setText method
of the Question class.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
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 ChoiceQuestion class needs to:
• Display the question text.
• Display the answer choices.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 35
Overriding Methods
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 36
section_3/ChoiceQuestion.java
1 import java.util.ArrayList;
2
3 /**
4 A question with multiple choices.
5 */
6 public class ChoiceQuestion extends Question
7 {
8 private ArrayList<String> choices;
9
10 /**
11 Constructs a choice question with no choices.
12 */
13 public ChoiceQuestion()
14 {
15 choices = new ArrayList<String>();
16 }
17
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 37
section_3/ChoiceQuestion.java
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
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 38
section_3/ChoiceQuestion.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 39
section_3/QuestionDemo2.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
section_3/QuestionDemo2.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 41
section_3/QuestionDemo2.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 42
Syntax 9.2 Calling a Superclass Method
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Self Check 9.11
Answer: The method is not allowed to access the instance
variable text from the superclass.
What is wrong with the following implementation of the display
method?
public class ChoiceQuestion
{
. . .
public void display()
{
System.out.println(text);
for (int i = 0; i < choices.size(); i++)
{
int choiceNumber = i + 1;
System.out.println(choiceNumber + ": " + choices.get(i));
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Self Check 9.11
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));
}
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Self Check 9.13
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?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Self Check 9.14
Answer:
public String getName()
{
return "*" + super.getName();
}
In the Manager class of Self Check 7, override the getName
method so that managers have a * before their name (such as
*Lin, Sally).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Self Check 9.15
Answer:
public double getSalary()
{
return super.getSalary() + bonus;
}
In the Manager class of Self Check 9, override the getSalary
method so that it returns the sum of the salary and the bonus.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 48
Common Error: Accidental Overloading
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 49
Syntax 9.3 Constructor with Superclass Initializer
Copyright © 2014 by John Wiley & Sons. All rights reserved. 50
Polymorphism
 Problem: to present both Question and ChoiceQuestion with
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 Question superclass has methods for displaying and
checking.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 51
Polymorphism
 We can simply declare the parameter variable of the
presentQuestion method to have the type Question:
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Polymorphism
 The variable q knows 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Polymorphism
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
section_4/QuestionDemo3.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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
section_4/QuestionDemo3.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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 57
section_4/QuestionDemo3.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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Self Check 9.16
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;
d. SavingsAccount account2 = account;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Self Check 9.17
Answer: It belongs to the class BankAccount or one of its subclasses.
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?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Self Check 9.18
Answer:
Question[] quiz = new Question[SIZE];
Declare an array quiz that can hold a mixture of Question and
ChoiceQuestion objects.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 61
Self Check 9.19
Answer: You cannot tell from the fragment—cq may be
initialized with an object of a subclass of ChoiceQuestion.
The display method of whatever object cq references is
invoked.
Consider the code fragment
ChoiceQuestion cq = . . .; // A non-null value
cq.display();
Which actual method is being called?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Self Check 9.20
Answer: No. This is a static method of the Math class. There
is no implicit parameter object that could be used to
dynamically look up a method.
Is the method call Math.sqrt(2) resolved through dynamic method
lookup?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 64
Object: The Cosmic Superclass
Figure 9 The Object Class Is the Superclass of Every Java Class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 65
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 66
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]"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 67
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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 68
Overriding the equals Method
Figure 10 Two References to Equal Objects
Copyright © 2014 by John Wiley & Sons. All rights reserved. 69
Overriding the equals Method
Figure 11 Two References to the Same Object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 70
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;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 71
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 72
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 73
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;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 74
Self Check 9.21
Answer: Because the implementor of the PrintStream class
did not supply a toString method.
Why does the call
System.out.println(System.out);
produce a result such as java.io.PrintStream@7a84e4?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 75
Self Check 9.22
Answer: The second line will not compile. The class Object
does not have a method length.
Will the following code fragment compile? Will it run? If not, what
error is reported?
Object obj = "Hello"; System.out.println(obj.length());
Copyright © 2014 by John Wiley & Sons. All rights reserved. 76
Self Check 9.23
Answer: The code will compile, but the second line will throw
a class cast exception because Question is not a
superclass of String.
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();
Copyright © 2014 by John Wiley & Sons. All rights reserved. 77
Self Check 9.24
Answer: There are only a few methods that can be invoked
on variables of type Object.
Why don’t we simply store all objects in variables of type Object?
Copyright © 2014 by John Wiley & Sons. All rights reserved. 78
Self Check 9.25
Answer: The value is false if x is null and true otherwise.
Assuming that x is an object reference, what is the value of x
instanceof Object?

More Related Content

What's hot

Icom4015 lecture4-f16
Icom4015 lecture4-f16Icom4015 lecture4-f16
Icom4015 lecture4-f16
BienvenidoVelezUPR
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
BienvenidoVelezUPR
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
BienvenidoVelezUPR
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
BienvenidoVelezUPR
 
Icom4015 lecture3-s18
Icom4015 lecture3-s18Icom4015 lecture3-s18
Icom4015 lecture3-s18
BienvenidoVelezUPR
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
BienvenidoVelezUPR
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
BienvenidoVelezUPR
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
BienvenidoVelezUPR
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
BienvenidoVelezUPR
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
BienvenidoVelezUPR
 
Java small steps - 2019
Java   small steps - 2019Java   small steps - 2019
Java small steps - 2019
Christopher Akinlade
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"
Gouda Mando
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
Mahmoud Ouf
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
rajni kaushal
 
05slide
05slide05slide
Java codes
Java codesJava codes
Java codes
Hussain Sherwani
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
Blue Elephant Consulting
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
Mahmoud Ouf
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
Gus Sandoval
 

What's hot (20)

Icom4015 lecture4-f16
Icom4015 lecture4-f16Icom4015 lecture4-f16
Icom4015 lecture4-f16
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
Icom4015 lecture3-s18
Icom4015 lecture3-s18Icom4015 lecture3-s18
Icom4015 lecture3-s18
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
Java small steps - 2019
Java   small steps - 2019Java   small steps - 2019
Java small steps - 2019
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"Java™ (OOP) - Chapter 6: "Arrays"
Java™ (OOP) - Chapter 6: "Arrays"
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
05slide
05slide05slide
05slide
 
Java codes
Java codesJava codes
Java codes
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
 

Similar to Icom4015 lecture8-f16

Java htp6e 09
Java htp6e 09Java htp6e 09
Java htp6e 09
Ayesha ch
 
Sun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock ExamSun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock Exam
Yasser Ibrahim
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class Inheritance
It Academy
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdet
DevLabs Alliance
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
devlabsalliance
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
DevLabs Alliance
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
kristinatemen
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
Raghavendra V Gayakwad
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
EasyStudy3
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
Journey's diary developing a framework using tdd
Journey's diary   developing a framework using tddJourney's diary   developing a framework using tdd
Journey's diary developing a framework using tdd
eduardomg23
 
Bt0074, oops with java
Bt0074, oops with javaBt0074, oops with java
Bt0074, oops with java
smumbahelp
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
HimanshuPandey957216
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
Jyothsna Sree
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
VishnuSupa
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.com
KeatonJennings91
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injection
Neoito
 

Similar to Icom4015 lecture8-f16 (20)

Java htp6e 09
Java htp6e 09Java htp6e 09
Java htp6e 09
 
Sun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock ExamSun Certified Enterprise Architect Scea Mock Exam
Sun Certified Enterprise Architect Scea Mock Exam
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class Inheritance
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdet
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Journey's diary developing a framework using tdd
Journey's diary   developing a framework using tddJourney's diary   developing a framework using tdd
Journey's diary developing a framework using tdd
 
Bt0074, oops with java
Bt0074, oops with javaBt0074, oops with java
Bt0074, oops with java
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.com
 
Neoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injectionNeoito — Design patterns and depenedency injection
Neoito — Design patterns and depenedency injection
 

Recently uploaded

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 

Recently uploaded (20)

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 

Icom4015 lecture8-f16

  • 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
  • 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
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 5 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 Car object in algorithms that manipulate Vehicle objects  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
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 6 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.
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 section_1/Question.java 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
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 8 section_1/Question.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 }
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 9 section_1/QuestionDemo1.java 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
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 10 section_1/QuestionDemo1.java Program Run: Who was the inventor of Java? Your answer: James Gosling true
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 11 Self Check 9.1 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. Consider classes Manager and Employee. Which should be the superclass and which should be the subclass?
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 12 Self Check 9.2 Answer: CheckingAccount and SavingsAccount both inherit from the more general class BankAccount. What are the inheritance relationships between classes BankAccount, CheckingAccount, and SavingsAccount?
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 13 Self Check 9.3 Answer: The classes Frame, Window, and Component in the java.awt package, and the class Object in the java.lang package. What are all the superclasses of the JFrame class? Consult the Java API documentation or Appendix D.
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 14 Self Check 9.4 Answer: Vehicle, Truck, Motorcycle Consider the method doSomething(Car c). List all vehicle classes from Figure 1 whose objects cannot be passed to this method.
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Self Check 9.5 Answer: It shouldn’t. A quiz isn’t a question; it has questions. Should a class Quiz inherit from the class Question? Why or why not?
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 16 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 ChoiceQuestion class, 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.
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 17 Implementing Subclasses  A subclass inherits all methods that it does not override. Figure 4 The ChoiceQuestion Class is a Subclass of the Question Class.
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 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
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Implementing Subclasses A ChoiceQuestion object differs from a Question object 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 ChoiceQuestion class shows these choices so that the respondent can choose one of them.
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 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<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.
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 Implementing Subclasses  UML of ChoiceQuestion and Question Figure 5 The ChoiceQuestion Class Adds an Instance Variable and a Method, and Overrides a Method
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 Syntax 9.1 Subclass Declaration
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 Implementing Subclasses  A ChoiceQuestion object  You can call the inherited methods on a subclass object: choiceQuestion.setAnswer("2");  The private instance variables of the superclass are inaccessible.  The ChoiceQuestion methods cannot directly access the instance variable answer.  ChoiceQuestion methods must use the public interface of the Question class to access its private data.
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 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); } }
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25 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);
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26 Self Check 9.6 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)
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Self Check 9.7 Suppose the class Employee is declared as follows: public class Employee { private String name; private double baseSalary; public void setName(String newName) { . . . } public void setBaseSalary(double newSalary) { . . . } public String getName() { . . . } public double getSalary() { . . . } } Declare a class Manager that inherits from the class Employee and adds an instance variable bonus for storing a salary bonus. Omit constructors and methods. Continued
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Self Check 9.7 Answer: public class Manager extends Employee { private double bonus; // Constructors and methods omitted }
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Self Check 9.8 Answer: name, baseSalary, and bonus Which instance variables does the Manager class from Self Check 7 have?
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Self Check 9.9 Answer: public class Manager extends Employee { . . . public double getSalary() { . . . } } In the Manager class, provide the method header (but not the implementation) for a method that overrides the getSalary method from the class Employee.
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 31 Self Check 9.10 Answer: getName, setName, setBaseSalary Which methods does the Manager class from Self Check 9 inherit?
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 32 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  Error! public class ChoiceQuestion extends Question { private ArrayList<String> choices; private String text; // Don’t! . . . }
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 33 Common Error: Replicating Instance Variables from the Superclass  The constructor compiles, but it doesn’t set the correct text!  The ChoiceQuestion constructor should call the setText method of the Question class.
  • 34. Copyright © 2014 by John Wiley & Sons. All rights reserved. 34 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 ChoiceQuestion class needs to: • Display the question text. • Display the answer choices.
  • 35. Copyright © 2014 by John Wiley & Sons. All rights reserved. 35 Overriding Methods  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.
  • 36. Copyright © 2014 by John Wiley & Sons. All rights reserved. 36 section_3/ChoiceQuestion.java 1 import java.util.ArrayList; 2 3 /** 4 A question with multiple choices. 5 */ 6 public class ChoiceQuestion extends Question 7 { 8 private ArrayList<String> choices; 9 10 /** 11 Constructs a choice question with no choices. 12 */ 13 public ChoiceQuestion() 14 { 15 choices = new ArrayList<String>(); 16 } 17 Continued
  • 37. Copyright © 2014 by John Wiley & Sons. All rights reserved. 37 section_3/ChoiceQuestion.java 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 Continued
  • 38. Copyright © 2014 by John Wiley & Sons. All rights reserved. 38 section_3/ChoiceQuestion.java 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
  • 39. Copyright © 2014 by John Wiley & Sons. All rights reserved. 39 section_3/QuestionDemo2.java 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
  • 40. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 section_3/QuestionDemo2.java 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
  • 41. Copyright © 2014 by John Wiley & Sons. All rights reserved. 41 section_3/QuestionDemo2.java 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
  • 42. Copyright © 2014 by John Wiley & Sons. All rights reserved. 42 Syntax 9.2 Calling a Superclass Method
  • 43. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Self Check 9.11 Answer: The method is not allowed to access the instance variable text from the superclass. What is wrong with the following implementation of the display method? public class ChoiceQuestion { . . . public void display() { System.out.println(text); for (int i = 0; i < choices.size(); i++) { int choiceNumber = i + 1; System.out.println(choiceNumber + ": " + choices.get(i)); } } }
  • 44. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Self Check 9.11 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)); } } }
  • 45. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Self Check 9.13 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?
  • 46. Copyright © 2014 by John Wiley & Sons. All rights reserved. 46 Self Check 9.14 Answer: public String getName() { return "*" + super.getName(); } In the Manager class of Self Check 7, override the getName method so that managers have a * before their name (such as *Lin, Sally).
  • 47. Copyright © 2014 by John Wiley & Sons. All rights reserved. 47 Self Check 9.15 Answer: public double getSalary() { return super.getSalary() + bonus; } In the Manager class of Self Check 9, override the getSalary method so that it returns the sum of the salary and the bonus.
  • 48. Copyright © 2014 by John Wiley & Sons. All rights reserved. 48 Common Error: Accidental Overloading  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.
  • 49. Copyright © 2014 by John Wiley & Sons. All rights reserved. 49 Syntax 9.3 Constructor with Superclass Initializer
  • 50. Copyright © 2014 by John Wiley & Sons. All rights reserved. 50 Polymorphism  Problem: to present both Question and ChoiceQuestion with 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 Question superclass has methods for displaying and checking.
  • 51. Copyright © 2014 by John Wiley & Sons. All rights reserved. 51 Polymorphism  We can simply declare the parameter variable of the presentQuestion method to have the type Question: 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
  • 52. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 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
  • 53. Copyright © 2014 by John Wiley & Sons. All rights reserved. 53 Polymorphism  The variable q knows 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.
  • 54. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Polymorphism  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.
  • 55. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 section_4/QuestionDemo3.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
  • 56. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 section_4/QuestionDemo3.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
  • 57. Copyright © 2014 by John Wiley & Sons. All rights reserved. 57 section_4/QuestionDemo3.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
  • 58. Copyright © 2014 by John Wiley & Sons. All rights reserved. 58 Self Check 9.16 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; d. SavingsAccount account2 = account;
  • 59. Copyright © 2014 by John Wiley & Sons. All rights reserved. 59 Self Check 9.17 Answer: It belongs to the class BankAccount or one of its subclasses. 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?
  • 60. Copyright © 2014 by John Wiley & Sons. All rights reserved. 60 Self Check 9.18 Answer: Question[] quiz = new Question[SIZE]; Declare an array quiz that can hold a mixture of Question and ChoiceQuestion objects.
  • 61. Copyright © 2014 by John Wiley & Sons. All rights reserved. 61 Self Check 9.19 Answer: You cannot tell from the fragment—cq may be initialized with an object of a subclass of ChoiceQuestion. The display method of whatever object cq references is invoked. Consider the code fragment ChoiceQuestion cq = . . .; // A non-null value cq.display(); Which actual method is being called?
  • 62. Copyright © 2014 by John Wiley & Sons. All rights reserved. 62 Self Check 9.20 Answer: No. This is a static method of the Math class. There is no implicit parameter object that could be used to dynamically look up a method. Is the method call Math.sqrt(2) resolved through dynamic method lookup?
  • 63. Copyright © 2014 by John Wiley & Sons. All rights reserved. 63 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
  • 64. Copyright © 2014 by John Wiley & Sons. All rights reserved. 64 Object: The Cosmic Superclass Figure 9 The Object Class Is the Superclass of Every Java Class
  • 65. Copyright © 2014 by John Wiley & Sons. All rights reserved. 65 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
  • 66. Copyright © 2014 by John Wiley & Sons. All rights reserved. 66 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]"
  • 67. Copyright © 2014 by John Wiley & Sons. All rights reserved. 67 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
  • 68. Copyright © 2014 by John Wiley & Sons. All rights reserved. 68 Overriding the equals Method Figure 10 Two References to Equal Objects
  • 69. Copyright © 2014 by John Wiley & Sons. All rights reserved. 69 Overriding the equals Method Figure 11 Two References to the Same Object
  • 70. Copyright © 2014 by John Wiley & Sons. All rights reserved. 70 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;
  • 71. Copyright © 2014 by John Wiley & Sons. All rights reserved. 71 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.
  • 72. Copyright © 2014 by John Wiley & Sons. All rights reserved. 72 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.
  • 73. Copyright © 2014 by John Wiley & Sons. All rights reserved. 73 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; }
  • 74. Copyright © 2014 by John Wiley & Sons. All rights reserved. 74 Self Check 9.21 Answer: Because the implementor of the PrintStream class did not supply a toString method. Why does the call System.out.println(System.out); produce a result such as java.io.PrintStream@7a84e4?
  • 75. Copyright © 2014 by John Wiley & Sons. All rights reserved. 75 Self Check 9.22 Answer: The second line will not compile. The class Object does not have a method length. Will the following code fragment compile? Will it run? If not, what error is reported? Object obj = "Hello"; System.out.println(obj.length());
  • 76. Copyright © 2014 by John Wiley & Sons. All rights reserved. 76 Self Check 9.23 Answer: The code will compile, but the second line will throw a class cast exception because Question is not a superclass of String. 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();
  • 77. Copyright © 2014 by John Wiley & Sons. All rights reserved. 77 Self Check 9.24 Answer: There are only a few methods that can be invoked on variables of type Object. Why don’t we simply store all objects in variables of type Object?
  • 78. Copyright © 2014 by John Wiley & Sons. All rights reserved. 78 Self Check 9.25 Answer: The value is false if x is null and true otherwise. Assuming that x is an object reference, what is the value of x instanceof Object?