Download Inheritance

Document related concepts
no text concepts found
Transcript
Chapter 9 - Inheritance
Copyright © 2014 by John Wiley & Sons. All rights reserved.
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 superclass Object and its
methods
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
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
Vehicle
Motorcycle
Car
Sedan
Truck
SUV
Figure 1 An Inheritance Hierarchy of Vehicle Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
Inheritance Hierarchies
 The class Car inherits from the class Vehicle
 The Vehicle class is the superclass
 The Car class is the subclass
Superclass
Subclass
Figure 2 Inheritance Diagram
Copyright © 2014 by John Wiley & Sons. All rights reserved.
4
Inheritance Hierarchies
 Inheritance lets you can reuse code instead of duplicating it.
 A class can be defined as a "subclass" of another class.
• The subclass inherits all data attributes of its superclass
• The subclass inherits all methods of its superclass
The subclass can:
Employee
-name
-Id
+getSalary()
+getName()
Add new functionality
Use inherited functionality
Override inherited functionality (modify)
SalariedEmployee
-weeklySalary
+calculateBonus()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CommissionEmployee
-grossSales
-commissionRate
+getCommissionRate()
5
parent/supercalss of
SalariedEmployee class and
CommissionEmployee
Employee
-name
-Id
+getSalary()
+getName()
+setID(id)
Inherited + overridden by subclasses
Inherited and used as it is by subclasses
Inherited and used as it is by subclasses
Additional attributes
Additional methods
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();
Copyright © 2014
by John Wiley & Sons. All rights reserved.
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
Employee
emp =
CommissionEmployee
new SalariedEmployee();
Person person = new CommissionEmployee();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
7
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.
8
Question
 What are candidate attributes and methods of
Question class?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
9
Answer
Question
-text : String
-answer : String
+ setText(String questionText)
+ setAnswer(String correctResponse)
+ checkAnswer(String response)
+ display()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
Programming Question
1. Implement the Question class
Question
-text : String
-answer : String
+ setText(String questionText)
+ setAnswer(String correctResponse)
+ checkAnswer(String response)
+ display()
2. Implementer the tester class QuestionDemo1 with
following code in main method:
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Question.java
/**
A question with a text and an answer.
*/
public class Question
{
private String text;
private String answer;
/**
Constructs a question with empty question and answer.
*/
public Question()
{
text = "";
answer = "";
}
/**
Sets the question text.
@param questionText the text of this question
*/
public void setText(String questionText)
{
text = questionText;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued
12
section_1/Question.java
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
Sets the answer for this question.
@param correctResponse the answer
*/
public void setAnswer(String correctResponse)
{
answer = correctResponse;
}
/**
Checks a given response for correctness.
@param response the response to check
@return true if the response was correct, false otherwise
*/
public boolean checkAnswer(String response)
{
return response.equals(answer);
}
/**
Displays this question.
*/
public void display()
{
System.out.println(text);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
13
QuestionDemo1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
/**
This program shows a simple quiz with one question.
*/
public class QuestionDemo1
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Question q = new Question();
q.setText("Who was the inventor of Java?");
q.setAnswer("James Gosling");
q.display();
System.out.print("Your answer: ");
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Question
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.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Question
What are the inheritance relationships between classes
BankAccount, CheckingAccount, and
SavingsAccount?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
Answer
CheckingAccount and SavingsAccount both inherit
from the more general class BankAccount.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
18
Question
Consider the method doSomething(Car c). List all
vehicle classes from Figure 1 whose objects cannot be
passed to this method.
Vehicle
Motorcycle
Car
Sedan
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Truck
SUV
19
Answer
doSomething(Car c)
Vehicle
Motorcycle
Car
Sedan
Truck
SUV
Answer: Vehicle, Truck, Motorcycle
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
Question
Should a class Quiz inherit from the class Question?
Why or why not?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
21
Answer
It shouldn’t. A quiz isn’t a question; it has questions.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
Implementing Subclasses
 A programmer makes a subclass by modifying another
class.
 E.g. To get a ChoiceQuestion class, implement it as a
subclass of Question
Copyright © 2014 by John Wiley & Sons. All rights reserved.
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 superclass objects!
Copyright © 2014 by John Wiley & Sons. All rights reserved.
24
Implementing Subclasses
Figure 4 The ChoiceQuestion Class is a Subclass of the Question Class.
• Inside ChoiceQuestion methods, the private instance variables of the superclass are
inaccessible.
•E.g. Inside ChoiceQuestion methods:
text=“Does java use a compiler, interpreter or both?”;
return answer;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
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?”);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
Implementing Subclasses
 Method declaration in subclasses:
• The subclass inherits all public methods from the superclass.
• You declare any methods that are new to the subclass.
• You override (i.e. change) the implementation of inherited
methods if the inherited behavior is not appropriate.
• Override a method:
– supply a new implementation for an inherited method
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
Implementing Subclasses
 How is ChoiceQuestion object different from Question
object?
1.
Its objects store the various choices for the answer.
2.
There is a method for adding answer choices (addChoice method).
3.
The display method of the ChoiceQuestion class shows these choices
(overriden) so that the respondent can choose one of them.
Overridden by subclass
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
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.
29
Syntax 9.1 Subclass Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Implementing Subclasses
A ChoiceQuestion object

Inside ChoiceQuestion class implementation it is ok to call public superclass
methods as its own:
•
E.g. Inside a ChoiceQuestion class method:
setAnswer(“A”);

//call superclass setAnswer method
An outside classes can call the inherited methods on a subclass object:
choiceQuestion.setAnswer("2");

If an outside classes call overridden method display method on a
ChoiceQuestion object overridden behavior is executed:
choiceQuestion.display()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
//call ChoiceObject overriden implementation
31
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.
32
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.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
34
Programming Question
 Implement the ChoiceQuestion class. Declare additional variables and
implement addChoice method
Overridden by subclass
 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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
Answer
public class Question
{
private String text;
private String answer;
public Question()
text = "";
answer = "";
}
Question.java
{
public Question(String text, String answer)
{
this.text = text
this.answer = answer;
}
public void setText(String questionText)
text = questionText;
}
{
public void setAnswer(String correctResponse){
answer = correctResponse;
}
public boolean checkAnswer(String response){
return response.equals(answer);
}
public void display() {
System.out.println(text);
}
public String getText() {
return text;
}
Copyright © 2014 by John Wiley
} & Sons. All rights reserved.
36
Answer
ChoiceQuestion.java
import java.util.ArrayList;
public class ChoiceQuestion extends Question
{
// This instance variable is added to the subclass
private ArrayList<String> choices;
public ChoiceQuestion()
{
choices = new ArrayList<String>();
}
// This method is added to the subclass
public void addChoice(String choice, boolean correct)
{
choices.add(choice);
if(correct)
setAnswer(choice);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
Answer
QuestionDemo.java
import java.util.Scanner;
public class QuestionDemo
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Question q = new Question();
q.setText("Who was the inventor of Java?");
q.setAnswer("James Gosling");
q.display();
System.out.print("Your answer: ");
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
ChoiceQuestion chq = new ChoiceQuestion();
chq.setText("Does java use a compiler, interpreter or both?");
chq.addChoice("compiler", false);
chq.addChoice("interpreter", false);
chq.addChoice("both", true);
chq.display();
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
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?”;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
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:
public ChoiceQuestion()
{
super(); //Question class should have a matching parameter list to one of
the constructors defined in superclass
choices = new ArrayList<String>();
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
Writing Subclass Constructors
 What if subclass constructor fails to call super?
public ChoiceQuestion()
{
choices = new ArrayList<String>();
}
• 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
41
Question
Suppose q is an object of the class Question and cq an
object of the class ChoiceQuestion. Which of the
following calls are legal?
a. q.setAnswer(response)
b. cq.setAnswer(response)
c. q.addChoice(choice, true)
d. cq.addChoice(choice, true)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Answer
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: a, b, d
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Common Error: Replicating Instance
Variables from the Superclass
 A subclass has no access to the private instance variables
of the superclass:
public ChoiceQuestion(String questionText)
{
text = questionText; // Error—tries to access
// private superclass variable
}
 Beginner's error:
• “solve” this problem by adding another instance variable with
same name
public class ChoiceQuestion extends Question
{
private ArrayList<String> choices;
private String text; // Don’t!
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
Common Error: Replicating Instance
Variables from the Superclass
 The constructor compiles, but it doesn’t set the correct
text!
 Correct way:
• The ChoiceQuestion constructor should call the setText
method of the Question class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
Overriding Methods
 If you are not satisfied with the behavior of an inherited
method,
• Override it by specifying a new implementation in the subclass.
 An overriding method can extend or replace the
functionality of the superclass method.
 E.g. The display method of the ChoiceQuestion class
needs to:
• Display the question text.
• Display the answer choices.
• So, superclass implementation of display is not sufficient!
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
Programming Question
 Modify ChoiceQuestion class so that it override the
display method in question class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
Answer
 Problem:
• ChoiceQuestion's display method can’t access the text variable
of the superclass directly because it is private.
 Solution:
• It can call the display method of the superclass, by using the
reserved word super
public void display()
{
// Display the question text
super.display(); // OK
// Display the answer choices
. . .
}
• super is a reserved word that forces execution of the superclass
method.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
Syntax 9.2 Calling a Superclass Method
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ChoiceQuestion.java
import java.util.ArrayList;
/**
A question with multiple choices.
*/
public class ChoiceQuestion extends Question
{
private ArrayList<String> choices;
/**
Constructs a choice question with no choices.
*/
public ChoiceQuestion()
{
choices = new ArrayList<String>();
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
50
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
Adds an answer choice to this question.
@param choice the choice to add
@param correct true if this is the correct choice, false otherwise
*/
public void addChoice(String choice, boolean correct)
{
choices.add(choice);
if (correct)
{
// Convert choices.size() to string
String choiceString = "" + choices.size();
setAnswer(choiceString);
}
}
public void display()
{
// Display the question text
super.display();
// Display the answer choices
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.
Continued
51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
QuestionDemo2.java
/**
This program shows a simple quiz with two choice questions.
*/
public class QuestionDemo2
{
public static void main(String[] args)
{
ChoiceQuestion first = new ChoiceQuestion();
first.setText("What was the original name of the Java language?");
first.addChoice("*7", false);
first.addChoice("Duke", false);
first.addChoice("Oak", true);
first.addChoice("Gosling", false);
ChoiceQuestion second = new ChoiceQuestion();
second.setText("In which country was the inventor of Java born?");
second.addChoice("Australia", false);
second.addChoice("Canada", true);
second.addChoice("Denmark", false);
second.addChoice("United States", false);
presentQuestion(first);
presentQuestion(second);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued
52
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
Presents a question to the user and checks the response.
@param q the question
*/
public static void presentQuestion(ChoiceQuestion q)
{
q.display();
System.out.print("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
53
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.
54
Question
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));
}
}
}
Answer: The type of the this reference is
ChoiceQuestion. Therefore, the display method of
ChoiceQuestion is selected, and the method calls
itself.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
Question
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?
Answer: Because there is no ambiguity. The subclass
doesn’t have a setAnswer method.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Polymorphism
 Polymorphism:
•
Ability of an object to take on many forms.
 Polymorphism in OOP:
• The most common use:
• A parent class reference is used to refer to a child class object.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
Polymorphism
 Overloading:
• when two methods in the same class have the same name but
different parameter types.
• Called static polymorphism.
• Can be determined at compile time
Copyright © 2014 by John Wiley & Sons. All rights reserved.
58
 Overriding:
• when a subclass method provides an implementation of a
superclass method whose parameter variables have the same
types.
• When overriding a method, the types of the parameter
variables must match exactly.
• Called dynamic polymorphism (most popular form of
polymorphism)
• Determined at run time
Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
Polymorphism
 E.g. 3 classes in inheritance hierarchy
public class Person{}
public class Student extends Person{}
public class GraduateStudent extends Student{}
 All following statements are valid (type of reference is a
superclass of type of object):
Person p = new Student();
Person p = new GraduateStudent();
Student s = new GraduatrStudent();
Object o = new GraduatrStudent();
 What does a call to p.display() print?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
Polymorphism
 Answer:
• It depends.
• You cannot find the version of display being called at compile
time (static binding is not possible).
• Instead, type of p will have to be tested during program
execution/runtime (dynamic binding).
 E.g.
• If different objects are assigned to p during execution, different
versions of display may be called:
p = new Student();
p.display(); // Calls display method in Student class
p = new GraduateStudent();
p.display(); // Calls display method in GraduateStudent class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
Polymorphism
 E.g. Question and ChoiceQuestion class hierarchy:
• Display method can be dynamically bound to a ChoiceQuestion object:
Question q = new ChoiceQuestion();
 Notice that we do not need to know the exact type of the
question to execute display method:
public static void presentQuestion(Question q)
{
q.display();
System.out.print("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(q.checkAnswer(response));
}
 We can substitute a subclass object whenever a
superclass object is expected:
ChoiceQuestion second = new ChoiceQuestion();
presentQuestion(second); // OK to pass a ChoiceQuestion
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
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.
63
section_4/QuestionDemo3.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;
/**
This program shows a simple quiz with two question types.
*/
public class QuestionDemo3
{
public static void main(String[] args)
{
Question first = new Question();
first.setText("Who was the inventor of Java?");
first.setAnswer("James Gosling");
ChoiceQuestion second = new ChoiceQuestion();
second.setText("In which country was the inventor of Java born?");
second.addChoice("Australia", false);
second.addChoice("Canada", true);
second.addChoice("Denmark", false);
second.addChoice("United States", false);
presentQuestion(first);
presentQuestion(second);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued
64
section_4/QuestionDemo3.java
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
Presents a question to the user and checks the response.
@param q the 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));
}
}
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
65
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.
66
Question
Assuming SavingsAccount is a subclass of BankAccount,
which of the following code fragments are valid in Java?
a. BankAccount account = new SavingsAccount();
b. SavingsAccount account2 = new BankAccount();
c. BankAccount account = null;
SavingsAccount account2 = account;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
Answer
Assuming SavingsAccount is a subclass of BankAccount,
which of the following code fragments are valid in Java?
a. BankAccount account = new SavingsAccount();
b. SavingsAccount account2 = new BankAccount();
c. BankAccount account = null;
SavingsAccount account2 = account;
Answer: a only.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
68
Question
If account is a variable of type BankAccount that holds a
non-null reference, what do you know about the object
to which account refers?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
69
Answer
It belongs to the class BankAccount or one of its subclasses.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
70
Object: The Cosmic Superclass
 Every class defined without an explicit extends clause
automatically extend Object
 The class Object is the direct or indirect superclass of
every class in Java.
 Some methods defined in Object:
• toString - which yields a string describing the object
• equals - which compares objects with each other
• hashCode - which yields a numerical code for storing the object in
a set
• getClass – return the runtime class of this object
Copyright © 2014 by John Wiley & Sons. All rights reserved.
71
Programming Question
 Insert the following code in QuestionDemo3.java and
run:
ChoiceQuestion chq = new ChoiceQuestion();
chq.setText("Does java use a compiler, interpreter or both?");
chq.addChoice("compiler", false);
chq.addChoice("interpreter", false);
chq.addChoice("both", true);
Question q = chq;
System.out.println(q.getClass());
Copyright © 2014 by John Wiley & Sons. All rights reserved.
72
 Returns:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
73
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.
74
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.
75
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.
76
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.
77
Overriding the equals Method
Figure 10 Two References to Equal Objects
Copyright © 2014 by John Wiley & Sons. All rights reserved.
78
Overriding the equals Method
Figure 11 Two References to the Same Object
Copyright © 2014 by John Wiley & Sons. All rights reserved.
79
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.
80
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.
81
Programming Question
 Modify your Rectangle.java class so you override the
equals method and toString method.
• equals method should return true only if x,y,width and height
matches to rectangle in parameter.
• To string method should print the x,y,width and height
parameters of object
• Sample output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
82
Answer
public class Rectangle
{
int x, y, width, height;
public Rectangle(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* overriden equals method
*
*/
public boolean equals(Object object)
{
Rectangle r = (Rectangle)object;
if(x==r.x && y==r.y && width==r.width && height==r.height)
return true;
return false;
}
public String toString()
{
return "Rectangle [x:"+x+" y:"+y+" width:"+width+" height:"+height+"]";
}
public static void main(String args[])
{
Rectangle r1 = new Rectangle(10,20,50,50);
Rectangle r2 = new Rectangle(10,20,50,50);
Rectangle r3 = new Rectangle(10,50,50,50);
System.out.println("r1= "+r1);
System.out.println("r2= "+r2);
System.out.println("r3= "+r3);
System.out.println("r1.equals(r2)"+r1.equals(r2));
System.out.println("r1.equals(r3)"+r1.equals(r3));
}
Copyright © 2014 by John Wiley
& Sons. All rights reserved.
}
83
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.
84
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.
85
Question
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.
86
Answer
Answer: Because the implementor of the PrintStream
class did not supply a toString method.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
87
Question
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.
88
Answer
Answer: The second line will not compile. The class
Object does not have a method length.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
89
Question
Will the following code fragment compile? Will it run? If not,
what error is reported?
Object obj = "Who was the inventor of Java?”;
Question q = (Question) obj;
q.display();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
90
Answer
Answer: The code will compile, but the second line will
throw a class cast exception because Question is not
a superclass of String.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
91
Question
Assuming that x is an object reference, what is the value of
x instanceof Object?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
92
Answer
Answer: The value is false if x is null and true
otherwise.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
93
When Not to Use Inheritance
 Inheritance is appropriate when:
• the new class “is a” particular case of the old class :
• The subclass must have every property of the superclass.
• E.g.
– A Car is a Vehicle.
– A SavingsAccount is an Account.
 Inheritance is inappropriate when:
• the words “is a” don’t fit.
• E.g.
• it wouldn’t make sense to say that a SavingsAccount is a Vehicle.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
94
94
Abstract Classes
 When you extend an existing class, you have the choice
whether or not to override the methods of the superclass.
 Sometimes, it is desirable to force programmers to
override a method.
 That happens when there is no good default for the
superclass, and only the subclass programmer can know
how to implement the method properly.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
95
Abstract Classes

E.g. Suppose we decides that every account type must have some monthly
fees.
• Therefore, a deductFees method should be added to the BankAccount
class:

But what should the method do?
• We could have the method do nothing.
• But then a programmer implementing a new subclass might
simply forget to implement the deductFees method:
• new account would inherit the do-nothing method of the superclass.

There is a better way:
• declare the deductFees method as an abstract method
Copyright © 2014 by John Wiley & Sons. All rights reserved.
96
Abstract Classes
 An abstract method has no implementation.
 This forces the implementers of subclasses to specify
concrete implementations of this method.
 You cannot construct objects of classes with abstract
methods.
 A class for which you cannot create objects is called an
abstract class.
 A class for which you can create objects is sometimes
called a concrete class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
97
Abstract Classes
 In Java, you must declare all abstract classes with the
reserved word abstract:
 Which classes must be declared abstract?
1. A class that declares an abstract method
2. A class that inherits an abstract method without
overriding it
3. Optionally, if you want, declare classes with no abstract
methods as abstract.
•
Doing so prevents programmers from creating instances of that
class but allows them to create their own subclasses.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
98
Abstract Classes
 You CANNOT construct an object of an abstract class
 you can still have a variable whose type is an abstract
class.
• Actual object to which it refers must be an instance of a concrete
subclass
Copyright © 2014 by John Wiley & Sons. All rights reserved.
99
Abstract Classes
 Why use abstract classes?
• To force programmers to create subclasses.
• By specifying certain methods as abstract you avoid the trouble
of coming up with useless default methods that others might
inherit by accident.
 How do Abstract classes differ from interfaces?
• Unlike interfaces, abstract classes can have:
• instance variables,
• concrete methods and
• constructors.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
100
Programming Question

Implement the classes Shape (abstract) and Point class. Class diagram is
shown below:


Add a main method to Point class to create a point and print it.
A sample run is shown below:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
101
Answer
Shape.java
Point.java
import java.awt.Color;
import java.awt.Color;
abstract class Shape {
public class Point extends Shape {
public Color color;
int x, y;
public Shape(Color color) {
this.color = color;
}
public Point(int x, int y, Color color) {
super(color); //or setColor(color);
this.x = 0;
this.y = 0;
}
public void setColor(Color c)
{
color = c;
public double area() {
return 0;
}
}
public Color getColor() {
return color;
}
public double perimeter() {
return 0;
}
abstract public double area();
}
public String toString() {
return "point: x:" + x + " y:" + y+ " color:"+color;
}
public static void main(String args[]) {
Point p = new Point(100,100, Color.BLACK);
System.out.println(p);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
102
Final Methods and Classes
 Occasionally, you may want to prevent other programmers from
creating subclasses or from overriding certain methods.
• Opposite of abstract methods
 In these situations, you use the final reserved word
 E.g. String class in Java library is final:
• i.e. nobody can extend (create subclasses of) the String class
• The String class is meant to be immutable
• string objects can’t be modified by any of their methods.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
103
 You can also declare individual methods as final:
Class is not final
 All extending subclasses cannot override the
checkPassword method with another method that
simply returns true.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
104
Common Error
 Overriding Methods to Be Less Accessible
 If a superclass declares a method to be publicly accessible, you
cannot override it to be more private in a subclass.
 E.g. superclass: BankAccount
 E.g subclass: CheckingAccount
• The compiler does not allow this
Copyright © 2014 by John Wiley & Sons. All rights reserved.
105
Enumeration Types
 In many programs, you use variables that can hold one of a
finite number of values:
• E.g in TaxReturn class, status variable:
• Only could hold one of the values SINGLE or MARRIED.
• We arbitrarily declared SINGLE as the number 1 and MARRIED as 2.
 If, due to some programming error, the status variable is
set to another integer value (such as –1, 0, or 3), then the
programming logic may produce invalid results.
 In a simple program, this is not really a problem.
 But as programs grow over time, and more cases are added
(such as the “married filing separately” and “head of
household” categories), errors can slip in.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
106
 Java version 5.0 introduces a remedy: enumeration
types.
 An enumeration type has a finite set of values
 E.g.
 You can have any number of values, but you must
include them all in the enum declaration.
 You can declare variables of the enumeration type:
 Use the == operator to compare enumeration values:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
107
 It is common to nest an enum declaration inside a class:
 E.g.
 To access the enumeration outside the class in which it is
declared, use the class name as a prefix:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
108
Copyright © 2014 by John Wiley & Sons. All rights reserved.
109
 An enumeration type variable can be null.
 E.g.
• the status variable in the previous example can
actually have three values:
• SINGLE, MARRIED, and null.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
110
Programming Question
 Declare a new class FilingStatus.java with folliwing
code:
public enum FilingStatus{SINGLE, MARRIED}
 Modify the TaxReturn class to do the following:
• Declare getTax() method final
• Modify class to use FilingStatus for status.
 Original TaxReturn class can be downloaded from here
Copyright © 2014 by John Wiley & Sons. All rights reserved.
111
Answer
FilingStatus.java
public enum FilingStatus{SINGLE, MARRIED}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
112
TaxReturn.java
1 import java.util.Scanner;
2 /**
3
A tax return of a taxpayer in 2008.
4 */
5 public class TaxReturn
6 {
7
private static final double RATE1 = 0.10;
8
private static final double RATE2 = 0.25;
9
private static final double RATE1_SINGLE_LIMIT = 32000;
10
private static final double RATE1_MARRIED_LIMIT = 64000;
11
12
private double income;
13
private FilingStatus status;
14
15
/**
16
Constructs a TaxReturn object for a given income and
17
marital status.
18
@param anIncome the taxpayer income
19
@param aStatus either SINGLE or MARRIED
20
*/
21
public TaxReturn(double anIncome, FilingStatus aStatus)
22
{
23
income = anIncome;
24
status = aStatus;
25
}
26
CONTINUED..
Copyright © 2014 by John Wiley & Sons. All rights reserved.
113
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public final double getTax()
{
double tax1 = 0;
double tax2 = 0;
if (status == FilingStatus.SINGLE)
{
if (income <= RATE1_SINGLE_LIMIT)
{
tax1 = RATE1 * income;
}
else
{
tax1 = RATE1 * RATE1_SINGLE_LIMIT;
tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
}
}
else
{
if (income <= RATE1_MARRIED_LIMIT)
{
tax1 = RATE1 * income;
}
else
{
tax1 = RATE1 * RATE1_MARRIED_LIMIT;
tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);
}
}
return tax1 + tax2;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
114
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
83
84}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your income: ");
double income = in.nextDouble();
System.out.print("Are you married? (Y/N) ");
String input = in.next();
FilingStatus status;
if (input.equals("Y"))
{
status = FilingStatus.MARRIED;
}
else
{
status = FilingStatus.SINGLE;
}
TaxReturn aTaxReturn = new TaxReturn(income, status);
System.out.println("Tax: “ + aTaxReturn.getTax());
}
CONTINUED..
Copyright © 2014 by John Wiley & Sons. All rights reserved.
115