0% found this document useful (0 votes)
62 views132 pages

Java Class09 ch09 J1 HO

The document discusses inheritance and interfaces in object-oriented programming. It covers implementing subclasses that inherit and override methods from superclasses, as well as polymorphism and interface types. The chapter goals are to learn about inheritance, polymorphism, the Object superclass and its methods, and interface types. It provides examples of inheritance hierarchies with vehicles and quiz questions. It also discusses implementing subclasses, overriding methods, and planning a subclass that extends a superclass.

Uploaded by

翁堯廷
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views132 pages

Java Class09 ch09 J1 HO

The document discusses inheritance and interfaces in object-oriented programming. It covers implementing subclasses that inherit and override methods from superclasses, as well as polymorphism and interface types. The chapter goals are to learn about inheritance, polymorphism, the Object superclass and its methods, and interface types. It provides examples of inheritance hierarchies with vehicles and quiz questions. It also discusses implementing subclasses, overriding methods, and planning a subclass that extends a superclass.

Uploaded by

翁堯廷
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

CHAPTER 9

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.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 2
Contents
 Inheritance Hierarchies
 Implementing Subclasses
 Overriding Methods
 Polymorphism
 Object: The Cosmic Superclass
 Interface Types

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 3
9.1 Inheritance Hierarchies
 In object-oriented programming, inheritance
is a relationship between:
 A superclass: a more
generalized class

 A subclass: a more
specialized class

 The subclass ‘inherits’ data (variables) and


behavior (methods) from the superclass
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 4
A Vehicle Class Hierarchy
 General superclass

 Specialized
subclass

 More Specific subclass

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 5
The Substitution Principle
 Since the subclass Car “is-a” Vehicle
 Car (subclass) shares common
traits with Vehicle (superclass)
 You can substitute a Car object
in an algorithm that expects a
is-a
Vehicle object
The
method: void processVehicle(Vehicle v);
Call the
method with
Car myCar = new Car(. . .);
a Car object: processVehicle(myCar);
The ‘is-a’ relationship is represented by an arrow in
a class diagram and means that the subclass can
behave as an object of the superclass.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 6
Cont’d
 Why provide a method that processes
Vehicle objects instead of Car objects?
 That method is more useful because it can
handle any kind of vehicle (including Truck and
Motorcycle objects)

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 7
Quiz Question Hierarchy
 There are different types of quiz questions:
1) Fill-in-the-blank The ‘root’ of the hierarchy
2) Single answer choice is shown at the top.
3) Multiple answer choice
4) Numeric answer
5) Free Response

 A question can:
 Display it’s text
 Check for correct answer

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 8
Question.java (1)

The class Question is the


‘root’ of the hierarchy, also
known as the superclass

 Only handles Strings


 No support for:
 Approximate values
 Multiple answer
choice

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 9
Question.java (2)

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Jump to Calling Superclass Methods Page 10
QuestionDemo1.java

Creates an object of the


Question class and
uses methods.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 11
Programming Tip 9.1
 Use a Single Class for Variation in Values,
Inheritance for Variation in Behavior
 If two vehicles only vary by fuel efficiency,
use an instance variable for the variation,
not inheritance a Hybrid car
subclass??
// Car instance variable
double milesPerGallon;

 If two vehicles behave differently,


use inheritance
Be careful not to over-use
inheritance

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 12
9.2 Implementing Subclasses
 Consider implementing ChoiceQuestion to handle:

 Write a ChoiceQuestion class from scratch, with


methods to set up the question, display it, and
check the answer?
 Or you can use inheritance and implement
ChoiceQuestion as a subclass of the Question class.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 13
Cont’d
 Consider implementing ChoiceQuestion to handle:

In this section you will see


how to form a subclass and
how a subclass automatically
inherits from its superclass

 How does ChoiceQuestion differ from Question?


 It stores choices (1,2,3 and 4) in addition to the question
 There must be a method for adding multiple choices
• The display method will show these choices below the question,
numbered appropriately

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 14
Inheriting from the Superclass
 Subclasses inherit from the superclass:
 All public methods that it does not override
 All instance variables (do not need to declare them again)
 The Subclass can The subclasses has no access
 Add new instance variables to the private variable of the
super class
 Add new methods
 Change the implementation of inherited methods
(override methods)
Form a subclass by
specifying what is
different from the
superclass.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 15
Overriding Superclass Methods
 Can you re-use any methods of the Question class?
 Inherited methods perform exactly the same
 If you need to change how a method works:
• Write a new more specialized method in the subclass
• Use the same method name as the superclass method
you want to replace
• It must take all of the same parameters
 This will override the superclass method
 The new method will be invoked with the same method
name when it is called on a subclass object

A subclass can override a method


of the superclass by providing a
new implementation.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 16
Planning the subclass
 Use the reserved word extends to inherit from
Question
 Inherits text and answer variables
 Add new instance variable choices

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() { . . . }
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 17
Syntax 9.1: Subclass Declaration
 The subclass inherits from the superclass and
‘extends’ the functionality of the superclass

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 18
Implementing addChoice
 The method will receive two parameters
 The text for the choice
 A boolean value denoting if it is the correct choice or not
 It adds text as a choice, adds choice number to the
text and calls the inherited setAnswer method
public void addChoice(String choice, boolean correct)
{
choices.add(choice);
if (correct)
{
// Convert choices.size() to string
String choiceString = "" + choices.size();
setAnswer(choiceString);
} setAnswer() is the same as
} calling this.setAnswer()
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 19
Common Error 9.1
 Replicating Instance Variables from the Superclass
 A subclass cannot directly access private instance
variables of the superclass public class Question
{
private String text;
private String answer;
. . .
public class ChoiceQuestion extends Question
{
. . .
text = questionText; // Complier Error!
// tries to access private superclass variable

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 20
Common Error 9.1 (2)
 Do not try to fix the compiler error with a new instance
variable of the same name
public class ChoiceQuestion extends Question
{
private String text; // Second copy

 The constructor sets one text variable


 The display method outputs the other

How do you get access to the instance


variable, text, and to print the question?
(public interface)

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

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 22
9.3 Overriding Methods
 The ChoiceQuestion class needs a display
method that overrides the display method of the
Question class
 They are two different method implementations
 The two methods named display are:
 Question display
• Displays the instance variable text String
 ChoiceQuestion display
• Overrides Question display method
• Displays the instance variable text String
• Displays the local list of choices

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 23
i.e. Question

• Get access of private


variables text and answer:
using public interface
• addChoice method
• The display method needs to
display the question AND the
list of choices

Page 24
Calling Superclass Methods
 Consider the display method of the
ChoiceQuestion class
 It needs to display the question AND the list of choices

 text is a private instance variable of the superclass


 How do you get access to it to print the question?
 Call the display method of the superclass Question!
 From a subclass, preface the method name with: super.
public void display()
{
// Display the question text
super.display(); // OK

// Display the answer choices


. . .
} Page 25
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Cont’d
 If you omit the reserved word super
public void display()
{
// Display the question text
display(); // Error – invokes this.display()
. . .
}
 The implicit parameter this is of type
ChoiceQuestion, and there is a method
display in the ChoiceQuestion class, that
method will be called – but that is just the
method your are currently writing! The method
would call itself over and over.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 26
QuestionDemo2.java (1)

Creates two objects of the ChoiceQuestion


class, uses new addChoice method.

Calls presentQuestion (next page)

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Jump to polymorphism Page 27
QuestionDemo2.java (2)

Uses ChoiceQuestion
(subclass) display
method.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 28
ChoiceQuestion.java (1)

Inherits from Question class.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 29
ChoiceQuestion.java (2)

New addChoice method.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 30
ChoiceQuestion.java (3)

Overridden display method.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 31
Cont’d
 Use the inherit ChoiceQuestion subclass
from the Question superclass:
 Instance variable:
• Text
• Answer
• checkAnswer
• choice
 Public interface (Method)
• setText
• setAnswer
• display(overriding)
• addChoice
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 32
Common Error 9.3
 Accidental Overloading
println(int x);
println(String s); // Overloaded

 Remember that overloading is when two methods share


the same name but have different parameters
 Overriding is where a subclass defines a method with
the same name and exactly the same parameters as the
superclass method
• Question display() method
• ChoiceQuestion display() method
 If you intend to override, but change parameters, you will
be overloading the inherited method, not overriding it
• ChoiceQuestion display(printStream out) method
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 33
Common Error 9.4
 Forgetting to use super when invoking a
Superclass method
 Assume that Manager inherits from Employee
• getSalary is an overridden method of Employee
– Manager.getSalary includes an additional bonus
public class Manager extends Employee
{
. . .
public double getSalary()
{
double baseSalary = getSalary(); // Manager.getSalary
// a recursive call, which will never stop
// should be super.getSalary(); // Employee.getSalary
return baseSalary + bonus;
}
} Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 34
Special Topic 9.1
 Calling the Superclass Constructor
 When a subclass is instantiated, it will call the
superclass constructor with no arguments
 If you prefer to call a more specific constructor, you can
invoke it by using replacing the superclass name with
the reserved word super followed by ():
public ChoiceQuestion(String questionText)
A call to the
superclass {
constructor super(questionText);
choices = new ArrayList<String>();
}

 It must be the first statement in your subclass


constructor
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 35
Constructor with Superclass
 To initialize private instance variables in the
superclass, invoke a specific constructor

Syntax public ClassName(parameterType parameterName, …)


{
super(arguments);

}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 36
Cont’d
public class Question
{ // call the superclass constructor
private String text; with no arguments
private String answer; public class ChoiceQuestion extends Question
{ private ArrayList<String> choices;
public Question()
{ public ChoiceQuestion()
text = “”; {
answer = “”; choices = new ArrayList<String>();
} }
…}
public Question(String questionText)
{
text = questionText; // To initialize private instance variables in
answer = “”; the superclass, invoke a specific constructor
}
… public ChoiceQuestion(String questionText)
} {
super(questionText);
choices = new ArrayList<String>();
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 37
9.4 Polymorphism
 In previous sample programs
 QuestionDemo.java presented Question objects
 QuestionDemo2.java presented two ChoiceQuestion
objects
 Can we write a program that shows a mixture of both
question types?

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 38
Cont’d
 QuestionDemo2 passed two ChoiceQuestion
objects to the presentQuestion method
 How would we write a presentQuestion method that
displays both Question and ChoiceQuestion types?

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 just display the question and check whether the user supplied the
correct answer. The Question superclass has methods for this purpose.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 39
Cont’d
 We can substitute a subclass object whenever a
superclass object is expected (Ch9.1)
A subclass reference can be used when a superclass reference is expected.
ChoiceQuestion second = new ChoiceQuestion();

presentQuestion(second);
// OK to pass a ChoiceQuestion object instead of Question
public static void presentQuestion(Question q)

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 40
Cont’d
 When the presentQuestion method executes,
the object references stored in second and q
refer to the same object of type ChoiceQuestion

ChoiceQuestion second = new ChoiceQuestion();


. . .
presentQuestion(second);

public static void presentQuestion(Question q)


{
q.display();
. . .
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 41
}
Cont’d
 However, the variable q knows less than the full
story about the object to which it refers
Question ?
ChoiceQuestion ?

 Because q is a variable of type Question, you


can call the display and checkAnswer methods.
You cannot call the addChoice method, though—
it is NOT a method of the Question superclass.
• In this method call, q refers to a ChoiceQuestion.
• In another method call, q might refer to a plain Question or
an entirely different subclass of Question.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 42
Which display method was called?
 presentQuestion simply calls the display
method of whatever type is passed: we need NOT know
the exact type of the
public static void presentQuestion(Question q) question.
{
q.display();  If passed an object of the Question class:
. . .  Question display
 If passed an object of the ChoiceQuestion class:

 ChoiceQuestion display
The method called depends on the contents of the parameter variable q

• In the first case, q refers to a Question object, so


the Question.display method is called.
• But in the second case, q refers to a ChoiceQuestion, so
the ChoiceQuestion.display method is called, showing the list of
choices.

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

ChoiceQuestion second = new ChoiceQuestion();


. . .
presentQuestion(second);

public static void presentQuestion(Question q)


{
q.display(); • q refers to a ChoiceQuestion, so
. . . the ChoiceQuestion.display method
} is called, showing the list of choices.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 44
Polymorphism Benefits
 In Java, method calls are always determined by
the type of the actual object, not the type of the
variable containing the object reference
 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 makes programs easily extensible

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 45
QuestionDemo3.java (1)

Creates an object of
the Question class

Creates an object of the


ChoiceQuestion class, uses
new addChoice method.

Calls presentQuestion (next page)


passing both types of objects.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 46
QuestionDemo3.java (2)

Receives a parameter of
the super-class type

Uses appropriate
display method.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 47
Special Topic 9.2
 Dynamic Method Lookup and the Implicit Parameter
 Suppose we move the presentQuestion method to inside the
Question class
public class Question
{
void presentQuestion() // in Question class
{
display();
System.out.print("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(checkAnswer(response));
}
}
• and call it as follows:
ChoiceQuestion cq = new ChoiceQuestion();
cq.setText("In which country was the inventor of Java born?");
. . . Which display and checkAnswer
cq.presentQuestion(); methods will be called? Page 48
Dynamic Method Lookup
 Add the Implicit Parameter to the code to find out
 Because of dynamic method lookup, the ChoiceQuestion
versions of the display and checkAnswer methods are called
automatically.
 This happens even though the presentQuestion method is
declared in the Question class, which has no knowledge of the
ChoiceQuestion class.
The implicit parameter this here
public class Question is a reference to an object of
{ type ChoiceQuestion.
void presentQuestion()
{
this.display();
System.out.print("Your answer: ");
Scanner in = new Scanner(System.in);
String response = in.nextLine();
System.out.println(this.checkAnswer(response));
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 49
Special Topic 9.3
Why do you need to declare
 Abstract Classes abstract 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

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 50
Cont’d
How do you declare
 Abstract Classes abstract method?

 Solution: declare the deductFee method as an abstract method


public abstract void deductFees();

• An abstract method has no implementation


• This forces the implementors of subclasses to specify
concrete implementations of this method
• You cannot instantiate an object that has abstract methods
• Therefore the class is considered abstract
public abstract class Account
{
public abstract void deductFees();
// no method implementation
. . .
}

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 51
Cont’d
 Abstract Classes
 A class for which you cannot create objects is called an abstract
class
public abstract class Account
{
public abstract void deductFees(); // no implementation
}

public class SavingAccount extends Account // Not abstract


{

public void deductFees() // MUST Provide an implementation
{
… If you extend the abstract class, you must
} implement ALL abstract methods.
}
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 52
Abstract References
 A class that can be instantiated is called concrete class
 You cannot instantiate an object that has abstract methods
 But you can declare an object reference whose type is an
abstract class.
 The actual object to which it refers must be an instance of a
concrete subclass
public abstract class Account{. . .}
Account anAccount; // OK: Reference to abstract object
anAccount = new Account(); // Error: Account is abstract
anAccount = new SavingsAccount(); // Concrete class is OK
anAccount = null; // OK
 This allows for polymorphism based on even an abstract
class!
One reason for using abstract classes is to
force programmers to create subclasses.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 53
Cont’d
 Special Topic 9.3: Abstract Classes
 How you can force other programmers to
create subclasses of abstract classes and
override abstract methods
 Special Topic 9.4: Final Methods and
Classes
 Do the opposite and prevent other
programmers from creating subclasses or
from overriding certain methods

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 54
Special Topic 9.4 ↔ Topic 9.3
 Final Methods and Classes
 Final Classes
 You can also prevent programmers from creating subclasses
and override methods using final.
 The String class in the Java library is an example:
public final class String { . . . } nobody can extend
the String class

 When you have a reference of type String, it must contain a String


object, never an object of a subclass

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 55
Cont’d
 Final Methods and Classes
 Final Methods
 Example of a method that cannot be overridden:
public class SecureAccount extends BankAccount
{
. . .
public final boolean checkPassword(String password)
{
. . .
}
} nobody can override the checkPassword method
with another method that simply returns true

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 56
Special Topic 9.5
 Protected Access
 When trying to implement the display method of the
ChoiceQuestion class, the display method wanted to access
the instance variable text of the superclass, but it was private.
 We chose to use a method of the superclass to display the text.
 Java provides a more elegant solution
 The superclass can declare an instance variable as protected
instead of private
 protected data in an object can be public class Question
accessed by the methods of the {
object’s class and all its subclasses. protected String text;
 But it can also be accessed by all . . .
} Methods in ChoiceQuestion can
other classes in the same package!
access the text variable now

If you want to grant access to the data to subclass methods only,


consider making the accessor method protected.
Page 57
Cont’d To access the instance variable text
 Protected Access
Display()
 When trying to implement the display method of the
ChoiceQuestion class, the display method wanted to access
the instance variable text of the superclass, but it was private.
 We chose to use a method of the superclass to display the text.
 Java provides a more elegant solution Protected Access
 The superclass can declare an instance variable as protected
instead of private
 protected data in an object can be public class Question
accessed by the methods of the {
object’s class and all its subclasses. protected String text;
 But it can also be accessed by all . . .
}
other classes in the same package!

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 58
Cont’d
 Some programmers like the protected access
feature because it seems to strike a balance
between these two:
 absolute protection (private instance variable)
 no protection at all (public instance variable)
 However, the protected instance variables are
subject to the same kinds of problems as public
instance variable
• The designer of the superclass has NO control over
the authors of subclasses!

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 59
Steps to Using Inheritance
 When you work with a set of classes, some of which are
more general and others more specialized.
 This enables you to process objects of different classes in a uniform
way
 As an example, we will consider a bank that offers
customers the following account types:
1) A savings account that earns interest.
The interest compounds monthly and is based on the minimum monthly
balance.
2) A checking account that has no interest,
gives you three free withdrawals per month, and charges a $1 transaction
fee for each additional withdrawal.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 60
Cont’d
 The program will manage a set of accounts of both types
 It should be structured so that other account types can be added
without affecting the main processing loop.

 The menu: D)eposit W)ithdraw M)onth end Q)uit


 For deposits and withdrawals, query the account number and
amount. Print the balance of the account after each transaction.
 In the “Month end” command, accumulate interest or clear the
transaction counter, depending on the type of the bank account.
Then print the balance of all accounts.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 61
Cont’d
1) List the classes that are part of the hierarchy.
SavingsAccount
CheckingAccount

2) Organize the classes into an inheritance


hierarchy
Base on superclass BankAccount

3) Determine the common responsibilities.


a. Write Pseudocode for each task
b. Find common tasks

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 62
Cont’d

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 63
Cont’d
4) Decide which methods are overridden in subclasses.
 For each subclass and each of the common responsibilities, decide
whether the behavior can be inherited or whether it needs to be
overridden
5) Declare the public interface of each subclass.
 Typically, subclasses have responsibilities other than those of the
superclass. List those, as well as the methods that need to be
overridden.
 You also need to specify how the objects of the subclasses should
be constructed.
6) Identify instance variables.
 List the instance variables for each class. Place instance variables
that are common to all classes in the base of the hierarchy.
7) Implement constructors and methods.
8) Construct objects of different subclasses and process them.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 64
9.5 Object: The Cosmic Superclass
 In Java, every class that is declared WITHOUT an explicit
extends clause automatically extends the class Object.

The methods of the Object class are very general.


You will learn to override the toString method.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 65
Cont’d
 The Object class defines several very
general methods, including
 toString
• Yields a string describing the object (section 9.5.1)
 equals
• Compares objects with each other (section 9.5.2)
 hashCode
• Yields a numerical code for storing the object in a
set (special topic 15.1)

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 66
Cont’d
 Object class
 Methods:
clone(), equals(),getClass(), hashCode(), notify(),
notifyAll(), toString(), wait()

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 67
Writing a toString method
 The toString method:
 returns a String representation for each object.
 The Rectangle class (java.awt) has a
toString method
 You can invoke the toString method directly
Rectangle box = new Rectangle(5, 10, 20, 30);
String s = box.toString(); // Call toString directly
// Sets s to "java.awt.Rectangle[x=5,y=10,width=20,height=30]“

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 68
Cont’d
 The toString method can also be invoked
implicitly whenever you concatenate a String with
an object:
String object reference
System.out.println("box=" + box); // Call toString implicitly

 The Java compiler automatically invokes the toString method to


turn the object into a string:
 The result is the string
String
“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, and can override toString
 However, the printed output may be the hash code

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 69
Cont’d
 String concatenated (+) with an object
reference
 The toString method invoked automatically
 String + numbers
 The toString method is NOT involved
• Compiler will convert the numbers to strings
WITHOUT calling toString method since numbers
are not objects
• There is only a small set of primitive types the
compiler knows how to convert them to strings

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 70
Overriding the toString method
 Ex. Override the toString method for the BankAccount
class
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to something like "BankAccount@d24606bf"

 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:

if (stamp1.equals(stamp2)) . . . // same Contents?

 This is different from the == operator which compares the


two references:

if (stamp1 == stamp2) . . . // same Objects?

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 72
Overriding the equals method
 The Object class specifies the type of parameter as Object
public class Stamp
{
private String color;
private int value;
. . .
public boolean equals(Object otherObject)
{
. . .
} It compares two Objects but we
. . . need to compare two Stamps
}
The Stamp equals method must declare the same type of parameter
as the Object equals method to override it.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 73
Cont’d
 But the Object class knows nothing about stamps, so it
declares the otherObject parameter variable of the
equals method to have the type Object
 When overriding the method, you are not allowed to change
the type of the parameter variable Otherwise, it’s overload
 Cast the parameter variable to the class Stamp, then you
can compare the two stamps
public boolean equals(Object otherObject) Recall:
{ int num1 = (int)(1.8);
// num1 = 1
Stamp other = (Stamp) otherObject;
return color.equals(other.color) && value == other.value;
}

if (stamp1.equals(stamp2)) // same Contents?

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 74
The instanceof operator
 Recall: It is legal to store a subclass reference in
a variable declared as superclass reference type
ChoiceQuestion cq = new ChoiceQuestion();
Question q = cq; //OK
Object obj = cq; //OK

BankAccount account = new SavingsAccount();


 The opposite conversion is also possible:
 From a superclass reference to a subclass reference
 If you have a variable of type Object, and you know
that it actually holds a Question reference, you can
cast it: Note: if the obj refers to an object
Question q = (Question) obj; of unrelated type, then a “class
cast” exception is thrown
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 75
Cont’d
 To make sure it is an object of the Question type,
you can test it with the instanceof operator:
if (obj instanceof Question)
 instanceof is an
{
operator returns a boolean
Question q = (Question) obj;
 Not operate on numbers
}

 obj instanceof Question


It returns true if the type of obj is convertible to
Question
 This happens if obj refers to an actual Question or to
a subclass such as ChoiceQuestion

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 76
Syntax 9.3: Using instanceof
 Using the instanceOf operator also involves casting
 Returns true if you can safely cast one object to another
 Casting allows the use of methods of the new object
 Most often used to make a reference more specific
• Cast from an Object reference to a more specific class type
Syntax object instanceof TypeName

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]"
}
}

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 79
Cont’d
Recall:
•Original toString()
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to something like "BankAccount@d24606bf"
•Overridding toString()
public class BankAccount
{
public String toString()
{
// returns "BankAccount[balance=5000]" Not specific enough
return "BankAccount[balance=" + balance + "]";
}
}
•Use getclass (inherited from object) in the superclass (next slide)
–Instead of writing the type of object in a toString method

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 80
Cont’d
 Instead of writing the type of object in a toString method
• Use getclass (inherited from object) in the superclass
public class BankAccount
{  getClass method: obtain an object that
. . . describes a class and its properties
public String toString()  getname method: get the name of the class
{
return getClass().getName() + "[balance=" + balance + "]";
} // returns BankAccount[balance= 100]

 Then use inheritance, call the superclass toString first


public class SavingsAccount extends BankAccount
{
. . . This allows the superclass to output
public String toString() private instance variables
{
return super.toString() + "[interestRate=" + intRate + "]";
} // returns SavingsAccount[balance= 10000][interestRate= 5]
} Page 81
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Special Topic 9.7
 Inheritance and the equals Method
What if called stamp1.equals(x) where x was NOT a Stamp object?
Recall:
•Original equals()
if (stamp1.equals(stamp2))
•Overridding equals()
public boolean equals(Object otherObject)
{ Recall: if the otherobj refers to an
Stamp other = (Stamp) otherObject; object of unrelated type, then a
“class cast” exception is thrown
return color.equals(other.color) && value == other.value;
}
•Use instanceof operator This test is not specific enough.
if (otherobj instanceof Stamp) It would be possible for otherObject to
belong to some subclass of Stamp.
{
Stamp other = (Stamp) otherobj;
}
•Use getClass method Page 82
Cont’d
 Better way: Use the getClass method to compare your
exact class to the passed object to make sure
public boolean equals(Object otherObject) Insures comparison of
the same types
{
if (otherObject == null) { return false; }
if (getClass() != otherObject.getClass()) { return false; }
Stamp other = (Stamp) otherObject;
return color.equals(other.color) && value == other.value;
}

if (stamp1.equals(stamp2))
//stamp1.getClass() == stamp2.getClass()

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 83
Cont’d
 When you implement equals in a subclass, you should
first call equals in the superclass to check whether the
superclass instance variables match
public CollectibleStamp extends Stamp
{
private int year;

public boolean equals(Object otherObject)
{
if (!super.equals(otherObject)) {return false;}
CollectibleStamp other = (CollectibleStamp) otherObject;
return year == other.year;
}
}

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 84
9.6 Interface Types
 The method that computes the average balance in an array of
BankAccount objects:
public static double average(BankAccount[] objects)
{
if(objects.length == 0) {return 0;}
double sum = 0;
for(BankAccount obj:objects)
{
sum = sum + obj.getBalance();
}
return sum/objects.length;
}
 The method that computes the average area in an array of Country
objects:
public static double average(Country[] objects)
{
if(objects.length == 0) {return 0;}
double sum = 0;
for(Country obj:objects) Same computing algorithm
{ but the details of
sum = sum + obj.getArea(); measurement differ
}
return
Copyright © 2013 by John Wiley sum/objects.length;
& Sons. All rights reserved. Page 85
}
Cont’d
 Use the interface type Measurable to
implement a “universal” method for
computing averages for different objects:
public static double average(Measurable[] objects)
{
if(objects.length == 0) {return 0;}
double sum = 0;
for(Measurable obj:objects)
{
sum = sum + obj.getMeasure();
}
return sum/objects.length;
}

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 86
Syntax 9.4: Interface Types
 An interface declaration and
a class that implements the interface.
• All methods are abstract
• All methods are public
• Cannot have instance variable
• Cannot have static methods

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 87
Cont’d
Syntax
Declaring: public interface InterfaceName
{
method declarations
}

Implementing: public class ClassName implements InterfaceName,...


{
instance variables
methods
}

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 88
Cont’d
 An interface is a special reference type of
declaration that lists a set of methods and their
signatures
 A class that ‘implements’ the interface must implement
ALL of the methods of the interface
 It is similar to a class, but there are differences:
• All methods in an interface type are abstract:
» They have a name, parameters, and a return type, but
they don’t have an implementation
• All methods in an interface type are automatically public
• An interface type cannot have instance variables
• An interface type cannot have static methods
public interface Measurable
{
double getMeasure();
} Page 89
Cont’d
 It is often possible to design a general and
reusable mechanism for processing objects by
focusing on the essential operations that an
algorithm needs.
 You use interface types to express these
operations.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 90
Using Interface Types
 We can use the interface type Measurable to
implement a “universal” static method for
computing averages: public interface Measurable
{
double getMeasure();
}

public static double average(Measurable[] objs)


{
if (objs.length == 0) return 0;
double sum = 0; By using an interface type for a
for (Measurable obj : objs) parameter variable, a method
{ can accept objects from many
sum = sum + obj.getMeasure(); classes.
}
return sum / objs.length;
}

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 91
An Implementation Diagram
Interfaces are tagged
with a “stereotype”
indicator «interface»

The dashed line with an arrow is used to


denote implements relationships

The Measurable interface expresses


what all measurable objects have in
common

It shows how the


same average method can compute
the average of a collection of bank
accounts or countries.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 92
Implementing an Interface
 A class can be declared to implement an interface
 The class must implement all methods of the interface
public class BankAccount implements Measurable
{
Use the implements reserved
public double getMeasure()
{ word in the class declaration.
return balance;
}
. . . public class Country implements Measurable
} {
public double getMeasure()
{
return area; The methods of the interface
} must be declared as public
. . .
}
A reference to a BankAccount or Country can be converted to a Measurable
reference
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 93
MeasureableDemo.java (1)

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 94
MeasureableDemo.java (2)

public class BankAccount implements Measurable


{
public double getMeasure()
public interface Measurable
{
{ return balance;
double getMeasure(); }
} . . . Page 95
}
Cont’d
 Recall:
public static double average(BankAccount[] objects)
{
if(objects.length == 0) {return 0;}
double sum = 0;
for(BankAccount obj:objects)
{
sum = sum + obj.getBalance();
}
return sum/objects.length;
}

public static double average(Country[] objects)


{
if(objects.length == 0) {return 0;}
double sum = 0;
for(Country obj:objects)
{
sum = sum + obj.getArea();
}
return sum/objects.length;
} Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 96
Cont’d
 Using interface type:
Measurable interface MeasurableDemo class with main method
public interface Measurable public static double average(Measurable[] objs)
{ {
double getMeasure(); if (objs.length == 0) return 0;
} double sum = 0;
for (Measurable obj : objs)
{
sum = sum + obj.getMeasure();
}
return sum / objs.length;
}

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

• Interfaces can reduce the coupling between classes


• UML notation:
• Interfaces are tagged with a “stereotype” indicator «interface»
• A dotted arrow with a triangular tip denotes the “is-a” relationship
between a class and an interface
• A dotted line with an open v-shaped arrow tip denotes the “uses”
relationship or dependency

• Note that DataSet is decoupled from


BankAccount and Coin
implement

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++;
}

public Coin getMaximum()


{
return maximum;
}
}
Cont’d
public class DataSet // Modified for BankAccount objects
{
private double sum;
private BankAccount maximum;
private int count;
...
public void add(BankAccount x)
{
sum = sum + x.getBalance();
if (count == 0 || maximum.getBalance() < x.getBalance())
maximum = x;
count++;
}

public BankAccount getMaximum()


{
return maximum;
}
}
Cont’d

• 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

• What is the type of the variable x?


• x should refer to any class that has a getMeasure method

• In Java, an interface type is used to specify required


operations:
public interface Measurable
{
double getMeasure();
}

• Interface declaration lists all methods that the interface type


requires
Generic DataSet for Measurable Objects
public class DataSet
{
private double sum;
private Measurable maximum;
private int count;
...
public void add(Measurable x)
{
sum = sum + x.getMeasure();
if (count == 0 || maximum.getMeasure() < x.getMeasure())
maximum = x;
count++;
}

public Measurable getMaximum()


{
return maximum;
}
}
ch09/measure1/DataSetTester.java
1 /**
2 This program tests the DataSet class. Program Run:
3 */ Average balance: 4000.0
4 public class DataSetTester Expected: 4000
5 { Highest balance: 10000.0
6 public static void main(String[] args) Expected: 10000
7 { Average coin value: 0.13333333333333333
8 DataSet bankData = new DataSet(); Expected: 0.133
9 Highest coin value: 0.25
10 bankData.add(new BankAccount(0)); Expected: 0.25
11 bankData.add(new BankAccount(10000));
12 bankData.add(new BankAccount(2000));
13
14 System.out.println("Average balance: " + bankData.getAverage());
15 System.out.println("Expected: 4000");
16 Measurable max = bankData.getMaximum();
17 System.out.println("Highest balance: " + max.getMeasure());
18 System.out.println("Expected: 10000");
19
20 DataSet coinData = new DataSet();
21
22 coinData.add(new Coin(0.25, "quarter"));
23 coinData.add(new Coin(0.1, "dime"));
24 coinData.add(new Coin(0.05, "nickel"));
25
26 System.out.println("Average coin value: " + coinData.getAverage());
27 System.out.println("Expected: 0.133");
28 max = coinData.getMaximum();
29 System.out.println("Highest coin value: " + max.getMeasure());
30 System.out.println("Expected: 0.25");
31 }
32 }
Inheritance vs. Interface
 In Java, multiple inheritance is NOT permitted
public class EraserPencil extends Eraser, Pencil {
. . .
} //Error – not possible

public class LiquidPaper extends Eraser{


. . .
} //OK public class MechanicalPencil extends Pencil {
. . .
} //OK

 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 {. . . }

public class EraserPencil extends Eraser, Pencil {. . .}


//Error – not possible Page 107
Cont’d
 Class implement Interface
public class A implements Listener {
public void listen() {. . . }
}
public class B implements Listener, Runnable {
public void listen() {. . . }
public void run() {. . . }
}
public class C implements MultiInterface {
public void listen() {. . . }
public void run() {. . . }
}
public class D extends A implements Runnable, AnotherRun {
public void run() {. . . }
public int run(int period) {. . . }
}

D ref = new D();


ref instanceof D; // true
ref instanceof Runnable; // true
ref instanceof AnotherRun; // true
ref instanceof A; // true
ref instanceof Listener; // true Page 108
The Comparable Interface
 The Java library includes a number of important
interfaces including Comparable
 It requires implementing one method: compareTo()
 It is used to compare two objects
 It is implemented by many objects in the Java API
 If may want to implement it in your classes to use
powerful Java API tools such as sorting
 It is called on one object, and is passed another
a.compareTo(b);
 Called on object a, return values include:
• Negative: a comes before b
• Positive: a comes after b
• 0: a is the same as b
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 109
Cont’d

 This interface imposes a total ordering on the objects of


each class that implements it.
 This ordering is referred to as the class's natural
ordering, and the class's compareTo method is referred
to as its natural comparison method.
 Lists (and arrays) of objects that implement this interface
can be sorted automatically by Collections.sort (and
Arrays.sort).
 Objects that implement this interface can be used as keys
in a sorted map or as elements in a sorted set, without the
need to specify a comparator.
Page 110
Cont’d
 Object Ordering
 A List l may be sorted as follows: Collections.sort(l);
• String and Date both implement the Comparable interface.
– If the List consists of String elements, it will be sorted into alphabetical
order.
– If it consists of Date elements, it will be sorted into chronological order.

•Comparable implementations provide


a natural ordering for a class, which
allows objects of that class to be
sorted automatically.

•If you try to sort a list, the elements of


which do NOT implement
Comparable, Collections.sort(list)
will throw a ClassCastException.

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

Using the type inside angle braces will


be covered further in the next chapter.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 112
A Comparable Example
 The BankAccount compareTo method compares accounts by balance.
 It takes one parameter of it’s own class type (BankAccount)
public class BankAccount implements Comparable<BankAccount>
{
. . .
public int compareTo(BankAccount other)
{
if (balance < other.getBalance()) { return -1; }
if (balance > other.getBalance()) { return 1; }
return 0;
} The methods of the interface must
. . . be declared as public
}

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);

 The array is now sorted by increasing balance


Implementing Java Library interfaces allows you to use the
power of the Java Library with your classes.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 114
Recall: Sorting Arrays
 When you store values into an array, you can
choose to either:
 Keep them unsorted (random order)

 Sort them (Ascending or Descending…)

 A sorted array makes it much easier to find a


specific value in a large data set
 The Java API provides an efficient sort method:
Arrays.sort(values); // Sort ascending all of the array
Arrays.sort(values, 0, currentSize); // partially filled

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

public interface Measurable public class BankAccount implements Measurable


{ {
double getMeasure(); public double getMeasure()
} {
return balance;
}
. . . Page 117
}
Special Topic 9.8
 Interface Constants
 The constants variables in an interface are public
static final by default
• you can (and should) omit the reserved words public static
final at declaration
 Interfaces cannot have instance variables, but it is legal
to specify constants public interface SwingConstants
{
int NORTH = 1;
int NORTHEAST = 2;
int EAST = 3;
. . .
}

public interface Measurable • To use this constant in your program


{ Measurable.OUNCE_PER_LITTER
double OUNCE_PER_LITTER = 33.814;
. . .
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 118
}
Special Topic 9.9
 Function Objects
 Interfaces work well IF all objects that need the service
are willing to implement the interface.
 The sole purpose of a function object is to execute a
single method
• This allows a non-implementing class to use the services of the
interface by creating a function object and using it’s method
 First, create a new interface
• The measure method measures an object and returns its
measurement.
• We use a parameter of type Object, the “lowest common
denominator” of all classes in Java, because we do not want to
restrict which classes can be measured.
public interface Measurer
{
double measure(Object anObject);
Copyright © 2013 by John Wiley & Sons. All rights reserved. } Page 119
Cont’d
 We add a parameter variable of type Measurere
to the average method:
public static double average(Object[] objs, Measurer meas)
{
if (objs.length == 0) { return 0; }
double sum = 0;
for (Object obj : objs)
{
sum = sum + meas.measure(obj);
}
return sum / objs.length;
}

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);

 An object such as lengthMeasurer is called a


function object
 The sole purpose of the object is to execute a single
method, in this case measure

•Instantiate an object of the Function object class


•Call your method that accepts an object of this type

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 122
Interfaces vs. Classes

An interface type is similar to a class, but there are several


important differences:
• All methods in an interface type are abstract; they don’t have an
implementation
• All methods in an interface type are automatically public
• An interface type does not have instance fields
Converting Between Class and Interface Types
• You can convert from a class type to an interface type, provided
the class implements the interface
• BankAccount account = new BankAccount(10000);
Measurable meas = account; // OK

Variables of Class and Interface Types


Cont’d
• You can convert from a class type to an interface type, provided
the class implements the interface
• BankAccount account = new BankAccount(10000);
Measurable meas = account; // OK
• Coin dime = new Coin(0.1, "dime");
Measurable x = dime; // Also OK
• Cannot convert between unrelated types:
Measurable x = new Rectangle(5, 10, 20, 30);
// ERROR
Because Rectangle doesn’t implement Measurable
Casts
• Add Coin objects to DataSet:
DataSet coinData = new DataSet();
coinData.add(new Coin(0.25, "quarter"));
coinData.add(new Coin(0.1, "dime"));
coinData.add(new Coin(0.05, ”nickel"));
Measurable max = coinData.getMaximum(); // Get the largest coin

• What can you do with max? It’s not of type Coin:


String name = max.getName(); // ERROR

• You need a cast to convert from an interface type to


a class type
• You know it’s a Coin, but the compiler doesn’t. Apply a cast:
Coin maxCoin = (Coin) max;
String name = maxCoin.getName();
Cont’d
• If you are wrong and max isn’t a coin, the program throws an
exception and terminates
• Difference with casting numbers:
• When casting number types you agree to the information loss
• When casting object types you agree to that risk of causing an exception
Summary: Inheritance
 A subclass inherits data and behavior from a
superclass.
 You can always use a subclass object in place of
a superclass object.
 A subclass inherits all methods that it does not
override.
 A subclass can override a superclass method by
providing a new implementation.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 128
Summary: Overriding Methods
 An overriding method can extend or replace the
functionality of the superclass method.
 Use the reserved word super to call a superclass
method.
 Unless specified otherwise, the subclass constructor
calls the superclass constructor with no arguments.
 To call a superclass constructor, use the super
reserved word in the first statement of the subclass
constructor.
 The constructor of a subclass can pass arguments to a
superclass constructor, using the reserved word
super.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 129
Summary: Polymorphism
 A subclass reference can be used when a
superclass reference is expected.
 Polymorphism (“having multiple shapes”) allows us
to manipulate objects that share a set of tasks, even
though the tasks are executed in different ways.
 An abstract method is a method whose
implementation is not specified.
 An abstract class is a class that cannot be
instantiated.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 130
Summary: toString and instanceOf
 Override the toString method to yield a String
that describes the object’s state.
 The equals method checks whether two objects
have the same contents.
 If you know that an object belongs to a given class,
use a cast to convert the type.
 The instanceof operator tests whether an object
belongs to a particular type.

Copyright © 2013 by John Wiley & Sons. All rights reserved.


Page 131
Summary: Interfaces
 The Java interface type contains the return
types, names, and parameter variables of
 Unlike a class, an interface type provides no
implementation.
 By using an interface type for a parameter variable,
a method can accept objects from many classes.
 The implements reserved word indicates which
interfaces a class implements.
 Implement the Comparable interface so that
objects of your class can be compared, for
example, in a sort method.
Copyright © 2013 by John Wiley & Sons. All rights reserved.
Page 132

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy