Java Class09 ch09 J1 HO
Java Class09 ch09 J1 HO
INHERITANCE
AND
INTERFACES
Copyright © 2013 by John Wiley & Sons. All rights reserved. Slides by Donald W. Smith Final Draft
TechNeTrain.com 10/29/2011
Chapter Goals
To learn about inheritance
To implement subclasses that inherit and
override superclass methods
To understand the concept of polymorphism
To understand the common superclass
Object and its methods
To work with interface types
In this chapter, you will learn how the notion of
inheritance expresses the relationship
between specialized and general classes.
A subclass: a more
specialized class
Specialized
subclass
A question can:
Display it’s text
Check for correct answer
QuestionDemo2.java
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 21
Common Error 9.2
The use of the terminology super- and subclasses
may be confusing
The Subclass ChoiceQuestion is an ‘extended’ and more
powerful version of Question
It is larger (has an added instance variable, choice) and
more capable (has an addChoice method)
• Is it a ‘super’ version of Question?... NO.
Super- and Subclass terminology comes from set
theory
ChoiceQuestion is one of a subset of all objects that inherit from
Question
The set of Question objects is a superset of ChoiceQuestion
objects
Page 24
Calling Superclass Methods
Consider the display method of the
ChoiceQuestion class
It needs to display the question AND the list of choices
Uses ChoiceQuestion
(subclass) display
method.
ChoiceQuestion display
The method called depends on the contents of the parameter variable q
Page 43
Cont’d
Question first = new Question(); • q refers to
. . .
a Question object, so
presentQuestion(first);
the Question.display
public static void presentQuestion(Question q) method is called.
{
q.display();
. . .
}
Creates an object of
the Question class
Receives a parameter of
the super-class type
Uses appropriate
display method.
When you extend an existing class, you have the choice whether
or not to override the methods of the superclass
If it is desirable to force subclasses to override a method
of a base class, you can declare a method as abstract
• E.g. when there is no good default for the superclass
Example. The First National Bank of Java decides that every
account type must have some monthly fee
• The deductFee method should be added to the Account class
public class Account Assume the method do nothing,
{ then a programmer implementing
public void deductFees() {…}; a new subclass might simply
forget to implement the
. . .
deductFee method and inherit the
do-nothing method of the
superclass
All that is printed is the name of the class, followed by the hash
code which can be used to tell objects (Ch 10)
We want to know what is inside the object!
public class BankAccount Therefore, override the toString
{ method to yield a string that describes
public String toString() the object’s state.
{
return "BankAccount[balance=" + balance + "]";
// returns "BankAccount[balance=5000]"
}
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 71
Overriding the equals method
In addition to the toString method, the Object class
equals method checks whether two objects have the same
contents:
Page 77
Common Error 9.5
Don’t Use Type Tests
if (q instanceof ChoiceQuestion)) // Don’t do this
{
// Do the task the ChoiceQuestion way
}
else if (q instanceof Question))
{
// Do the task the Question way
}
This is a poor strategy. If a new class is added, then all
these queries need to be revised.
• When you add the class NumericQuestion
Let polymorphism select the correct method:
• Declare a method doTheTask in the superclass, Override it
in subclasses, and call
q.doTheTask();
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 78
Special Topic 9.6
Inheritance and the toString Method
Assume you want your toString method to be usable by
subclasses of your class
You CANNOT hardcoding the class name like this:
public class BankAccount
{
public String toString()
{
return "BankAccount[balance=" + balance + "]";
// returns "BankAccount[balance=5000]"
}
}
if (stamp1.equals(stamp2))
//stamp1.getClass() == stamp2.getClass()
BankAccount class
public class BankAccount implements Measurable
{ Country class
public double getMeasure() public class Country implements Measurable
{ {
return balance; public double getMeasure()
} {
. . . return area;
} Copyright © 2013 by John Wiley & Sons. All rights reserved. }
Page 97
. . .
UML Diagram of DataSet and Related Classes
use
More examples:
Using Interfaces for Algorithm Reuse
• Use interface types to make code more reusable
• We created a DataSet to find the average and maximum of a
set of numbers
• What if we want to find the average and maximum of a set of
BankAccount values?
Cont’d
• We would need to modify the DataSet class again:
public class DataSet // Modified for Coin objects
{
private double sum;
private Coin maximum;
private int count;
...
public void add(Coin x)
{
sum = sum + x.getValue();
if (count == 0 || maximum.getValue() <
x.getValue()) maximum = x;
count++;
}
• The algorithm for the data analysis service is the same in all
cases; details of measurement differ
• Classes could agree on a method getMeasure that obtains the
measure to be used in the analysis
• We can implement a single reusable DataSet class whose add
method looks like this:
sum = sum + x.getMeasure();
if (count == 0 || maximum.getMeasure() < x.getMeasure())
maximum = x;
count++;
Cont’d
However, in Interface
1. A class can implement one or more interface
(following slides)
2. Use the interface type to implement a “universal”
static method for any objects implement the interface
Reference: programming.im.ncnu.edu.tw
Page 106
Cont’d
Interface Declaration
public interface Listener {
double PI = 3.14149; //public static final
void listen(); //public abstract
}
public interface Runnalbe {
int PERIOD = 10;
void run();
}
public interface AnotherRun {
int PERIOD = 20;
void run();
int run(int);
}
Interface Inheritance
public interface ActionListener extends Listener {. . . }
public interface MultiInterface extends Listener, Runnalbe {. . . }
Page 111
The Comparable Type parameter
The Comparable interface uses a special type of
parameter that allows it to work with any type:
public interface Comparable<T> Or
{ public interface Comparable
int compareTo(T other); {
int compareTo(Object other);
}
}
The type <T> is a placeholder for an actual type of object
The class ArrayList class uses the same technique with
the type surrounded by angle brackets < >
ArrayList<String> names = new ArrayList<String>();
Or
public class BankAccount implements Comparable
{
. . .
public int compareTo(Object otherObject)
{
BankAccount other = (BankAccount) otherObject;
if (balance < other.getBalance()) { return -1; }
if (balance > other.getBalance()) { return 1; }
return 0;
}
. . .
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 113
}
Using compareTo to Sort
The Arrays.sort method uses the compareTo method to
sort the elements of the array
Once the BankAccount class implements the
Comparable interface, you can sort an array of bank
accounts with the Arrays.sort method:
BankAccount[] accounts = new BankAccount[3];
accounts[0] = new BankAccount(10000);
accounts[1] = new BankAccount(0);
accounts[2] = new BankAccount(2000);
Arrays.sort(accounts);
Page 115
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 116
Common Error 9.6
Forgetting to Declare Implementing Methods
as Public
The methods in an interface are public by default
• You don’t need to manual declare them as public
However, the methods in a class are not public by default
• You need to put the public reserved word when declaring a method
from an interface: public class BankAccount implements Measurable
{
• The compiler complains that the method has double getMeasure() // Oops—should be public
a weaker access level, namely package {
return balance;
access instead of public access. }
• The remedy is to declare the method as . . .
public. }
Page 120
Cont’d
When calling the method, you need to supply a
Measurer object
That is, you need to implement a class with a measure
method, and then create an object of that class
E.g. For measuring strings:
public class StringMeasurer implements Measurer
{
public double measure(Object obj)
{
String str = (String) obj; // Cast obj to String type
return str.length();
}
}
Page 121
Cont’d
Finally, we are ready to compute the average
length of an array of strings:
String[] words = { "Mary", "had", "a", "little", "lamb" };
Measurer strMeas = new StringMeasurer();
double result = average(words, strMeas);