Inheritance and Interfaces
Unit H
Inheritance
• IS-A relationship
Superclass
(Base class)
Subclass
(Derived class)
Subclass extends
Superclass
2
Clock Example of Inheritance
• class Clock
■ Fields? hr min
■ Methods: tick(), setTime(h,m)
• class AlarmClock
■ Fields? alarmHr, alarmMin
■ Methods: ring(), setAlarmTime(h,m)
3
Clock Example of Inheritance
-hour
Clock -min
getHour()
getMin()
toString()
AlarmClock
-alarmHour
-alarmMin
getAlarmHour()
getAlarmMin()
toString()
4
Syntax Clock myClock = new Clock();
AlarmClock myAlarm = new AlarmClock();
public class Clock public class AlarmClock extends Clock
{ {
private int hour; private int alarmHour;
private int min; private int alarmMin;
public int getHour()
{ public int getAlarmHour()
return hour; {
} return alarmHour;
public int getMin() }
{ public int getAlarmMin()
return min; {
} return alarmMin;
public void setTime(int inH, int inM) }
{
hour = inH;
min = inM; public void setAlarmTime(int inH, int inM)
} {
} alarmHour = inH;
alarmMin = inM;
}
}
5
Overriding Methods
public class NintendoGame
{
public void pressB()
{
jump();
}
}
public class SuperMario extends NintendoGame
{
public void pressB()
{
shoot();
}
}
6
Override Example
public class Clock public class BrokenClock extends Clock
{ {
private int hour;
private int min; public void setTime(int inH, int inM)
{
public void setHour(int inH) setHour(0);
{ setMin(0);
hour = inH; }
}
public void setMin(int inM) }
{
min = inM;
}
public void setTime(int inH, int inM)
{
setHour(inH); in a driver class, perhaps…
setMin(inM);
}
} Clock myClock = new Clock();
BrokenClock myBrokenClock = new BrokenClock();
myClock.setTime(12, 12);
myBrokenClock.setTime(12, 12);
myBrokenClock.setMin(20);
7
A Trickier Override Example
public class Clock
{
private int hour; public class BrokenClock extends Clock
private int min; {
public void setTime(int inH, int inM)
public void setTime(int inH, int inM) {
{ setHour(0);
hour = inH; setMin(0);
min = inM; }
}
public int getHour() public String toString()
{ {
return hour; return “HUH?”;
} }
public int getMin() }
{
return min;
}
public String getTime()
{ Clock myClock = new Clock();
return toString(); BrokenClock myBrokenClock = new BrokenClock();
}
public String toString()
{ myClock.setTime(12, 12);
return hour + “:” + min; myBrokenClock.setTime(12, 12);
}
} myClock.getTime();
myBrokenClock.getTime();
8
Constructors
• The constructor of a child class must call the constructor of
the parent class as its first statement
• super(<args>) calls the constructor of the base class
• If it is not explicitly done, the compiler will call the parents
class’ no-args constructor automatically (i.e. calling super())
public class Clock public class AlarmClock extends Clock
{ {
private int hour; private int alarmHour;
private int min; private int alarmMin;
public Clock(int h, int m) public AlarmClock(int h, int m, int ah, int am)
{ {
hour = h; super(h, m);
min = m; alarmHour = ah;
} alarmMin = am;
} } 9
}
super()
• To initialize fields that live in a base class
■ The parameters passed to super() must match
one of the constructors of the base class
■ super() must be the first line of subclass
constructor
■ If no super() is supplied, the no-args
constructor of the base class is called (so there
better be one!)
10
Invoking a Superclass’s Constructors
Let’s revisit our Clock example
public class Clock public class AlarmClock extends Clock
{ {
private int hour; private int alarmHour;
private int min; private int alarmMin;
//methods not shown //methods not shown
} }
What must the constructors of the two classes look like?
public Clock public AlarmClock
{ {
} } 11
Calling Methods in a Parent Class
• this vs. super keywords
public class Clock public class AlarmClock extends Clock
{ {
private int hour; private int aHour;
private int min; private int aMin;
public String toString() public String toString()
{ {
return hour + “:“ + min; String s = “Alarm is: “ + aHour + “:“ + aMin;
} return super.toString() + “ “ + s;
} }
}
12
Calling Superclass’s Methods
public class AlarmClock
{
//fields and constructors not shown
public void soundAlarm() { … }
//other methods not shown
}
public class FlashyAlarmClock extends AlarmClock
{
//fields and constructors not shown
public void soundAlarm()
{
flashLights();
super.soundAlarm();
}
//other methods not shown
}
13
Inheritance
Inheritance
• Whenever an object of a specific class is required, an object
of a subclass of that class can be used in its place
Phone[] phones = new Phone[5];
phones[0] = new iPhone();
phones[1] = new PixelPhone();
phones[2] = new Phone();
public void foo(Phone thePhone)
{
...
}
Phone p;
…
p = <ask the user for a phone? >; 14
Inheritance and Polymorphism
Polymorphism
• Ensures that the correct method is called for an object of a
specific type, even when the object is disguised by a reference to
a more generic type
Phone[] phones = new Phone[5];
phones[0] = new iPhone();
phones[1] = new PixelPhone();
phones[2] = new Phone();
for(Phone p : phones)
p.call();
• It’s automatic, there is no need to do anything special
• late or dynamic method binding: the decision on which method
to call is made when the program is running (not when it is
compiled)
15
Bird a = new Bird();
Eagle b = new Eagle();
Inheritance Penguin c = new Penguin();
1
public void try1(Bird x) 2
{ x.fly(); }
public void try2(Bird x)
{ x.talk(); }
public void try3(Eagle x) 5
{ x.fly(); }
3 6
public void try4(Eagle x) 4
{ x.eat(); }
try1(a);
public void try5(Eagle x) try1(b);
{ x.retrieve(); } try1(c); try5(a);
public void try6(Penguin x) try2(a); try5(b);
{ x.fly(); } try2(b); try6(a);
try2(c); try6(c);
public void try7(Penguin x)
{ x.eat(); } try3(a); try7(a);
try3(b); try7(c);
try4(a); try8(a);
public void try8(Penguin x)
{ x.talk(); } try4(b); try8(c); 16
Polymorphism
Bird a = new Bird();
Eagle b = new Eagle();
Penguin c = new Penguin();
Bird d = new Eagle();
Bird e = new Penguin();
Eagle f = new Penguin();
Eagle g = new Bird();
a.fly(); d.eat();
b.fly(); b.retrieve(); d.retrieve();
c.fly(); e.fly(); d.talk();
d.fly(); e.eat(); e.talk();
17
Abstract Classes
• Pig, Sheep, Chicken are your classes
• They all eat, have a number of legs and make a sound
• The parent might be BarnyardAnimal
• Can you actually create a BarnyardAnimal?
• BarnyardAnimal would be an abstract class
• Now you can create a parameter of type
BarnyardAnimal, and ask each how many legs it has,
or to make a sound
18
Syntax for an Abstract Class
public abstract class BarnyardAnimal
You can have concrete methods or abstract methods in
the class
■ What might be a concrete method of BarnyardAnimal?
getNumLegs() or any accessor methods
■ Abstract methods must be declared abstract
• public abstract int makeNoise();
■ Abstract methods must be defined in the inheriting class
■ Can we create objects from an abstract class?
19
Syntax for an Abstract Class
public abstract class BarnyardAnimal
{
private int numLegs;
public BarnyardAnimal(int legs)
{
numLegs = legs;
}
public abstract void makeNoise();
}
public class Chicken extends BarnyardAnimal
public class Pig extends BarnyardAnimal {
{ public static final int NUM_LEGS = 2;
public static final int NUM_LEGS = 4; public Chicken()
public Pig() {
{ super(NUM_LEGS);
super(NUM_LEGS); }
}
public void makeNoise()
{
public void makeNoise() /* implementation not shown */
{ }
/* implementation not shown */
} public Egg layEgg()
{ /* implementation not shown */ }
public void wallow() }
{ /* implementation not shown */ }
20
}
Abstract Classes
• Can we do this?
BarnyardAnimal rex = new BarnyardAnimal(4);
rex.makeNoise();
• Given:
public void foo(BarnyardAnimal betsy)
{
betsy.makeNoise();
}
• Is this legal?
public void test()
{
Pig p = new Pig();
p.wallow(); public void test2()
foo(p); {
BarnyardAnimal b = new Pig();
Chicken c = new Chicken(); b.wallow();
c.layEgg(); b.makeNoise();
foo(c); foo(b);
} }
21
Abstract Classes
public abstract class Player
{
public abstract int getNumber(); public static void main(String[] args)
} {
FunGame game = new FunGame();
HumanPlayer h = new HumanPlayer()
public class ComputerPlayer extends Player
ComputerPlayer c = new ComputerPlayer();
{
public int getNumber() Player[] competitors = new Player[2];
{ competitors[0] = h;
return (int)(Math.random() * 100) competitors[1] = c;
}
} int turn = 0;
while(true)
{
public class HumanPlayer extends Player
competitors[turn%2].getNumber();
{ turn++;
public int getNumber() }
{
Scanner console = new
Scanner(System.in);
return console.nextInt(); 22
}
Object class
• In Java, every class by default extends a
library class Object (from java.lang)
• Object is a concrete class Methods
public class Object redefined
{ (overridden)
public String toString {...} as necessary
public boolean equals (Object other){... }
// a few other methods
...
}
• The methods really aren’t useful unless they
are overridden!
23
Interfaces
• What is an interface?
• How have we used the term interface so
far in programming?
■ A class’ set of public methods
■ The things a client can do to a class
■ What is the interface for a radio?
24
Interfaces
• Sometimes we want two classes to share behavior but they
might not share an IS-A relationship.
• A Java interface is very similar to an abstract class
■ One or more abstract methods declared but left undefined
■ Do not use public abstract because ALL methods must be
left undefined
public interface Washable public interface Packable
{ {
String directions(); void pack();
void wash(); }
}
25
Interfaces
• A class that implements an interface does not have an IS-
A relationship necessarily
• A concrete class that implements an interface must
supply all the methods in the interface
• An abstract class that implements an interface may leave
some of the interface’s methods abstract.
public interface Washable
public class CottonShirt implements Washable
{
{
public String directions();
public String directions()
public void wash();
{ return “Hot water”; }
}
public void wash()
{
WashingMachine kenmore = new WashingMachine(); What else is washable?
kenmore.wash(this, “hot”);
}
//other methods not shown 26
}
Interfaces
• While Java does not support multiple
inheritance, a class can implement more than
one interface
• An interface provides a secondary data type to
objects of a class that implement the interface
■ CottonShirt has the type Washable as well
public void doLaundry(Washable item) Polymorphism: the
{ correct method is
System.out.println(item.directions()); called for any
item.wash(); specific type of
} Washable, e.g., a
CottonShirt 27
28
Classes vs. Interfaces (Similarities)
• A superclass provides a • An interface provides a
secondary data type to secondary data type to
objects of its subclasses. objects of classes that
implement that interface.
• An abstract class cannot be • An interface cannot be
instantiated instantiated
• A concrete subclass of an • A concrete class that
abstract class must define all implements an interface must
the inherited abstract define all the methods
methods. specified by the interface.
• A class can extend another • An interface can extend
class. A subclass can add another interface (called its
methods and override some superinterface) by adding
of its superclass’s methods. declarations of abstract
methods.
29
Classes vs. Interfaces (Differences)
• A class can extend • A class can implement any number of
only one class. interfaces.
• A class can have • An interface cannot have fields (except,
fields. possibly, some public static final constants).
• A class defines its • An interface has no constructors.
own constructors (or
gets a default
constructor).
• A concrete class has • All methods declared in an interface are
all its methods abstract.
defined. An abstract
class usually has one
or more abstract
methods.
• Every class is a part • An interface may belong to a small hierarchy
of a hierarchy of of interfaces, but this is not as common.
classes with Object
Casting
• What is casting for?
• Can I change the type of an object this way?
Bird a = new Bird();
Bird b = new Eagle();
What happens here? a.retrieve()
Here? b.retrieve()
How can we call retrieve?
What happens here? Penguin c = (Penguin)a;
30