
















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















































Chapter Objectives
After studying this chapter, you should be able to:
Write a polymorphic program using inheritance
-^ Write a polymorphic program using an interface -^ Build an inheritance hierarchy -^ Use the strategy and factory method patterns to make yourprograms more flexible -^ Override standard methods in the
Object
class
12.1.1: Dancing Robots—Example 1 (1/2)
import becker.robots.; /* A robot which "dances" towards the left. */ public class LeftDancer extends RobotSE{ public LeftDancer(City c, int str, int ave, Direction dir){ super(c, str, ave, dir);} public void move(){ this.turnLeft(); super.move();this.turnRight();super.move();this.turnRight();super.move();this.turnLeft(); } public void pirouette(){ this.turnLeft(4);} }
Object
+boolean equals(Object o)+String toString( )
Robot
-int curAvenue-int curStreet+Robot(City c, int str, int ave, ...)+void move( )+void turnLeft( )+void pickThing( )
RobotSE
+RobotSE(City c, int str, int a...)+void turnRight( )+void turnRight(int numTimes)+void turnLeft(int numTimes)+void move(int howFar)
RightDancer +RightDancer(City c, ...)+void move( )+void pirouette( )
LeftDancer +LeftDancer(City c, ...)+void move( )+void pirouette( )
12.1.1: Dancing Robots—Example 1 (2/2)
import becker.robots.*;public class Example1 extends Object{ public static void main(String[ ] args){ City danceFloor = new City(); LeftDancer ld = new LeftDancer(danceFloor, 4, 1, Direction.NORTH);RightDancer rd = new RightDancer(danceFloor, 4, 2,
Direction.NORTH
);
for (int i = 0; i < 4; i++){ ld.move(); rd.move(); } ld.pirouette();rd.pirouette(); } }
R
L^ L
R
12.1.2: Dancing Robots—Example 2 (2/2)
Principles
The type of the reference (
Robot ld
) determines the
names
of the
methods that can be called.
You can call any method named in
Robot
or its superclasses
(move
,^ turnLeft
,^ pickThing
, … but
not
pirouette
The type of the object (
new LeftDancer
) determines which method
is actually executed.
When asked to
move
, it will move the way
LeftDancer
s move,
not the way ordinary
Robot
s move.
Therefore, one message (e.g.
move
) can execute many ways, each
one specialized to the object that receives it. How is this useful? When you don’t know what kind of object youhave and you just want it to do “the right thing.”
12.1.2: Dancing Robots—Example 3
import becker.robots.*;public class Example3 extends Object{ public static void main(String[ ] args){ City danceFloor = new City(); Robot[ ] chorusLine = new Robot[6]; // Could also do this with a loop for 600 robots! chorusLine[0] = new LeftDancer(danceFloor, 4, 1,
Direction.NORTH
);
chorusLine[1] = new RightDancer(danceFloor, 4, 2,
Direction.NORTH
);
chorusLine[2] = new Robot(danceFloor, 4, 3,
Direction.NORTH
);
chorusLine[3] = new LeftDancer(danceFloor, 4, 4,
Direction.NORTH
);
chorusLine[4] = new RightDancer(danceFloor, 4, 5,
Direction.NORTH
);
chorusLine[5] = new Robot(danceFloor, 4, 6,
Direction.NORTH
);
for (int i = 0; i < 4; i++){ for (int j = 0; j < chorusLine.length; j++) { chorusLine[j].move();} } } }
12.1.2: Abstract Classes
public abstract class Dancer extends RobotSE{ public Dancer(City c, int str, int ave, Direction d){ super(c, str, ave, d);} /** Require all subclasses to implement*^ a pirouette method. */ public abstract void pirouette(); } An
abstract
class has at least one abstract method – a method with no
body. Such a class cannot be instantiated. To be useful, it must have atleast one subclass. That subclass must implement the abstractmethod(s).The abstract class
can
be used to declare variables. Such variables can
be used to call the methods, including the abstract methods.
RobotSE methods omitted LeftDancer +LeftDancer(...)+void move( )+void piro uette( )
RightDancer +RightDancer(...)+void move( )+void pirouette( )
DanceHall -Dancer[ ] chorusLine m ethods omitted
*^
Dancer +Dancer(...)+vo id
pirouette
( )
12.1.3: Examples of Polymorphism (1/5)
Programs using polymorphism often exhibit the following structure:
Abstract
Concrete
Concrete
Client
[ ] list
client
uses the services of another class. In the previous examples,
the client was the
main
method that had an array of robots.
The
abstract class
is used to declare variables in the client. In the
previous examples, the abstract class was
Robot
or
Dancer
The
concrete classes
implement methods named in the abstract class.
In the previous examples,
LeftDancer
and
RightDancer
were the
concrete classes.
12.1.3: Examples of Polymorphism (3/5)
Example: A Drawing Program
Oval
+Oval(...)+vo id d raw (...)
Rectangle +Rectangle(...)+vo id d raw (...)
Drawing
-Shape[ ] shapes m ethods omitted
*^
Shape
-int x, y-int w idth, height+Shap e(...)+vo id setLo cation(...)+vo id setSize(...)+vo id
draw
(...)
Text
-String characters+Text(...)+vo id d raw (...)
12.1.3: Examples of Polymorphism (4/5)
Example: Monitoring Alarms
FireAlarm +FireAlarm(...)+int getAlarmState( )
MotionDetector +MotionDetecto r(...)+int getAlarmState( )
Monitor
-Alarm[ ] alarms m ethods omitted
*^
Alarm
-Lo cation location-int urgency+int NORMAL+int OFF_LINE+int AL ARM+Alarm(...)+Location getL ocatio n()+int getUrgency( )+int
getAlarmState
( )
BrokenWindowAlarm +BrokenWind ow Alarm(...)+int getAlarmState( )
12.1.4: Polymorphism via Interfaces
A Java interface can be used in place of the abstract class. This allowseach concrete class to extend a different class, if necessary.
StrategyInterface + int getN ex tMove
( )
AskUserStrategy +int getNextMove( )
FirstLegalStrategy +int getNextMove( )
Player
-StrategyInterface mStrategy
RandomStrategy +int getNextMo ve( )
AIStrategy +int getNextMove( )
JDialog
12.1.5: The Substitution Principle
An object of one type, A, can substitute for an object of another type,B, if A can be used any place that B can be used.In a polymorphic program:
A concrete class substitutes for the abstract class.
-^ Different substituted concrete classes may behave differently.
Case Study: A Poor Design (1/x)
Bank
-MinBalAccount[ ] mbAccts-PerUseAccount[ ] puAccts... +Bank( )-MinBalAccount findMinBalAccount(
int acctNum) -PerUseAccount findPerUseAccount(
int acctNum) +void deposit(int acctNum, double amt)+void withdraw(int acctNum, double amt)...
MinBalAccount
+double balance+boolean balBelow+int acctNum+MinBalAccount(...)+void deposit(double amt)+void withdraw(double amt)+void transfer(double amt,
MinBalAccount toAccount)
+void transfer(double amt,
PerUseAccountt toAccount) PerUseAccount
+double balance+int numWithdraws+int acctNum+PerUseAccount(...)+void deposit(double amt)+void withdraw(double amt)+void transfer(double amt,
MinBalAccount toAccount)
+void transfer(double amt,
PerUseAccount toAccount)
UI
-Bank bank-TextInput in+UI(Bank aBank)+void eventLoop( )
Case Study: A Poor Design (2/x)
public class Bank{^ // Partially-filled arrays of accounts, one array for each kind of account. private MinBalAccount[ ] mbAccts = new MinBalAccount[3];private int numMBAccts = 0;private PerUseAccount[ ] puAccts = new PerUseAccount[3];private int numPUAccts = 0; /** Deposit money into an account.* @param acct
The account number for the deposit
The amount of the deposit.
*/
public void deposit(int acct, double amt){ MinBalAccount mba = this.findMinBalAccount(acct); if (mba != null){ mba.deposit(amt);} else{ PerUseAccount pua = this.findPerUseAccount(acct); if (pua != null){ pua.deposit(amt);} else{ System.out.println(
"Account "
" not found."
);
} } } }