1School of Information Technologies / The University of Sydney 2011-S2
Software Development in Java
Week10 • Semester 2 • 2015
Inheritance
Polymorphism
Abstract class
Final class
Comments on Quiz 2
Assignment Part 1 (implementation Demo)
in Lab Session
School of Information Technologies / The University of Sydney 2011-S2
Introduction to Inheritance
2School of Information Technologies / The University of Sydney 2011-S2
Introduction to Inheritance
Inheritance is the process by which a new class is derived from
an existing class.
The existing class that contains common features or behaviors is
called as the base class, or superclass
E.g. the Person class
Define some classes as extensions of the superclass to inherit
all the fields and methods from the superclass called as
subclasses, or derived classes
E.g. define a Student class on the basis of Person class,
i.e., Student class is a subclass of Person class
Inheritance is a powerful way to support software reuse.
School of Information Technologies / The University of Sydney 2011-S2
Introduction to Inheritance
Superclass – subclass
Inheritance implies an “is-a” relationship
A subclass object “is-a” a superclass object
The superclass generalizes subclasses
Examples:
Student “is-a” Person
ChequeAccount “is-a” Account
In general, a subclass is a special kind of superclass.
3School of Information Technologies / The University of Sydney 2011-S2
Someone writes code for the superclass, and we reuse it in the
subclass, without re-writing from scratch
We use java keyword extends to define the inheritance
In Java, a class can directly extend only one superclass
It implicitly extends the Object class if nothing else is
declared.
The subclass inherits all fields and methods of the parent,
plus whatever is defined in the subclass itself
Code-reuse in Java
School of Information Technologies / The University of Sydney 2011-S2
Example: class inheritance with extends
public class Customer {
private double creditCardBalance;
private double chequeAccountBalance;
private String name;
...
class YoungCustomer extends Customer {
private int age;
…
YoungCustomer “is-a” Customer
YoungCustomer has all
the fields and methods
of Customer, plus a few
of its own.
superclass
subclass
4School of Information Technologies / The University of Sydney 2011-S2
Example: class inheritance with extends
class ElectricalAppliance {
protected int energyRating;
…
public void switchOn() { …
…
}
class Fridge extends ElectricalAppliance {
protected int freezerCapacity;
…
public void defrost() {
}
Fridge “is-a” ElectricalAppliance
Fridge implicitly has an instance
field:
• protected int energyRating
and a method
• public void switchOn(),
• as well as the fields and methods
defined in its own code.
superclass
subclass
School of Information Technologies / The University of Sydney 2011-S2
Access modifiers
Access modifiers control the accessibility/visibility of fields and methods in
a Java class
default [when there is no modifier stated, it is default access]
public
private
protected
Situation default public private protected
Accessible to class
from same package?
Yes Yes No Yes
Accessible to class
from a different
package?
No Yes No Subclasses: yes
Otherwise: no
If you want to use/access superclass members in the subclass, you
must make the members in the superclass either protected or public.
5School of Information Technologies / The University of Sydney 2011-S2
Inheritance: Fields
School of Information Technologies / The University of Sydney 2011-S2
Inheriting Fields
Fields
1. Inherit
Fields inheritance: all fields from the superclass are
automatically inherited
Subject to access modifiers, a subclass has no access to private
fields of its superclass
2. Add
You can add fields: supply a new field that doesn't exist in the
superclass
6School of Information Technologies / The University of Sydney 2011-S2
Inheritance: Constructors
School of Information Technologies / The University of Sydney 2011-S2
Constructors and inheritance
public class Circle{
double x;
double y;
double r;
...
public Circle(double a, double b, double c){
x=a; y=b; r=c;
}
...
Syntax is super(...);
Usually, superclass
constructor initializes
the inherited fields
using a subset of the
parameters in the
subclass constructor
Then continue to
initialize the added
instance variables.
Constructors
The first statement in any subclass constructor should be a call to a
superclass constructor (super(…))
public class ColoredCircle extends Circle{
int colour;
public ColoredCircle(double a, double b, double c, int d)
{
super(a,b,c);
colour = d;
}
7School of Information Technologies / The University of Sydney 2011-S2
Inheritance: Methods
Inherited methods
Added methods
Overridden methods
School of Information Technologies / The University of Sydney 2011-S2
Methods
How do we know which method to apply?
public class Customer {
...
class YoungCustomer extends Customer {
…
…
// calling a method from either subclass or superclass
…
superclass
subclass
client
class
8School of Information Technologies / The University of Sydney 2011-S2
Inheriting Methods
Inherit method:
In this case, no new implementation of a superclass method
Superclass methods can be applied to the subclass objects
public class Customer {
...
public boolean inDebt() {
return (wealth() < 0);
}
...
class YoungCustomer extends Customer {
… /* inherit inDebt() from super &
no new implementation of inDebt() in the subclass*/
...
YoungCustomer babyface = new YoungCustomer(“Baby”, 100, 100);
If (babyface.inDebt()) System.out.println(“Bad Baby!”);
...
Superclass
m
ethod is used
su
pe
rc
la
ss
su
bc
la
ss
an
ot
he
r
cl
as
s
School of Information Technologies / The University of Sydney 2011-S2
Adding Methods
Add method:
In subclass, define a new method that doesn't exist in the superclass
New methods can be applied only to subclass objects
public class Customer {
... // no method birthdayGift() defined
..
class YoungCustomer extends Customer {
…
public void birthdayGift() {
depositChequeAccount(10);
}
..
...
YoungCustomer babyFace = new YoungCustomer(“Baby”, 100, 100);
if (babyFace.sameDay(Date.today)) babyFace.birthdayGift();
…
Subclass
m
ethod is
used
su
pe
rc
la
ss
su
bc
la
ss
an
ot
he
r
cl
as
s
9School of Information Technologies / The University of Sydney 2011-S2
Overriding Methods
Override method:
The subclass has a different implementation of a superclass method
The subclass method must have same signature (same name, same
parameter types), same return type as the superclass method
public class Customer {
...
public void writeCheque(int amount) {
chequeAccountBalance = chequeAccountBalance – amount - fee;
}
...
class YoungCustomer extends Customer {
private int age;
…
public void writeCheque(int amount) {
chequeAccountBalance = chequeAccountBalance – amount ;
}
...
superclass
subclass
Sa
m
e
si
gn
at
ur
e
School of Information Technologies / The University of Sydney 2011-S2
Overriding Methods
Override method:
The subclass has a different implementation of a superclass method
The subclass method must have same signature (same name, plus
same parameter types) and same return type as the superclass
method
public class Customer {
...
public void writeCheque(int amount) {
chequeAccountBalance = chequeAccountBalance – amount - fee;
}
...
class YoungCustomer extends Customer {
private int age;
…
public void writeCheque(int amount) {
chequeAccountBalance = chequeAccountBalance – amount ;
}
...
O
verw
ritten by subclass
su
pe
rc
la
ss
su
bc
la
ss
10
School of Information Technologies / The University of Sydney 2011-S2
Overriding Methods
Override method:
If the method is invoked from an object of the subclass type,
then the overriding method is executed
public class Customer {
...
public void writeCheque(int amount) {
chequeAccountBalance = chequeAccountBalance – amount - fee;
}
...
class YoungCustomer extends Customer {
…
public void writeCheque(int amount) {
chequeAccountBalance = chequeAccountBalance – amount ;
}
...
su
pe
rc
la
ss
...
YoungCustomer babyFace = new YoungCustomer(“Baby”, 100, 100)
babyFace.writeCheque(20);
...
su
bc
la
ss
an
ot
he
r c
la
ss
Subclass
m
ethod is
used
School of Information Technologies / The University of Sydney 2011-S2
Overriding Methods
Override method:
Note
We can use the superclass method in the subclass
Use “super”: super.methodName(parameters)
in subclass
class YoungCustomer extends Customer {
…
public void writeCheque(int amount) {
super.writeCheque(amount);
chequeAccountBalance += fee;
}
...
11
School of Information Technologies / The University of Sydney 2011-S2
Aside:toString method
The toString method converts objects of a class to a string, usually
for printing.
Most classes in the Java platform have a method toString defined.
For example, Double.toString(2.0/3.0) returns the String
“0.6666666666666666”.
If you write your own method in your own class
Java automatically supplies a toString method (but it may
return something meaningless).
If you want an appropriate string representation of your objects
(for example, for printing), then you should override the
toString method supplied by Java with your own toString
method.
School of Information Technologies / The University of Sydney 2011-S2
public class CustomerTester {
public static void main(String[] args) {
Customer p = new Customer("Peter",-1276,423);
Customer m = new Customer("Mary", -24, 165);
System.out.println(p);
System.out.println(m);
}
toString: example
public class Customer {
private double creditCardBalance;
private double chequeAccountBalance;
private String name;
. ... ..
.....
Prints out
src5214.Customer@e48e1b
src5214.Customer@12dacd1
12
School of Information Technologies / The University of Sydney 2011-S2
toString: example
public class Customer {
private double creditCardBalance;
private double chequeAccountBalance;
private String name;
. ... ..
public String toString(){
return name + "\t" + creditCardBalance + "\t" +
chequeAccountBalance;
}
.....public class CustomerTester {
public static void main(String[] args) {
Customer p = new Customer("Peter",-1276,423);
Customer m = new Customer("Mary", -24, 165);
System.out.println(p);
System.out.println(m);
}
Prints out
Peter -1276 423
Mary -24 165
Same test class
School of Information Technologies / The University of Sydney 2011-S2
UML
(Unified Modeling Language)
13
School of Information Technologies / The University of Sydney 2011-S2
UML Diagrams
UML (Unified Modeling Language) notation is for conceptual
models, ideal for OO code structure!
Draw each class as a rectangle
Inheritance/generalization is shown by arrows with triangle
heads, from a subclass to a superclass
School of Information Technologies / The University of Sydney 2011-S2
UML Symbols
We use rectangles for classes and interfaces, like this:
and can add attributes and methods to them like this:
Class name
Constructors &
methods
fields
14
School of Information Technologies / The University of Sydney 2011-S2
UML Relations
We show relations among classes with different types of arrows.
School of Information Technologies / The University of Sydney 2011-S2
Inheritance Hierarchy
A superclass itself can extend another class: e.g.
ElectricalAppliance extends Object
The subclass implicitly inherits fields and methods in
superclass including those the superclass inherited –and so
on.
Inheritance from superclasses of the direct
superclass is called indirect inheritance.
A class can directly extend only one other class
The classes form a tree based on extends relationship. This
is the inheritance hierarchy.
15
School of Information Technologies / The University of Sydney 2011-S2
Inheritance Tree
School of Information Technologies / The University of Sydney 2011-S2
Example: Car class
16
School of Information Technologies / The University of Sydney 2011-S2
Description of the Car class
Class Car describes a car driven by a normal driver.
A car instance has instance fields for the name of the car, the
speed and position of the car, whether the accelerator and brake
are currently on or off.
Further, the class has static fields that describe the upper and
lower speed limits, and well as the friction force on the car.
The class contains getters and setters for all fields, as well as a
toString override method.
The behaviour of the car is described by the method drive(),
which essentially describes the behaviour of a normal driver:
If the speed is lower than the lower speed limit then the driver
accelerates.
If the speed exceeds the upper speed limit, then the driver
applies the brake.
Otherwise the driver keeps the status quo.
School of Information Technologies / The University of Sydney 2011-S2
17
School of Information Technologies / The University of Sydney 2011-S2
Car class
public class Car {
private double speed;
private double accelerationPower;
private double brakePower;
private boolean acceleratorOn;
private boolean brakeOn;
private double position;
private String name;
private static double lowerSpeedLimit = 80.0;
private static double upperSpeedLimit = 110.0;
private static double friction = 0.3;
…
fields
School of Information Technologies / The University of Sydney 2011-S2
Car class
public Car(String n, double p, double a, double b){
name = n;
position = p;
accelerationPower = a;
brakePower = b;
speed = 0.0;
acceleratorOn = true;
brakeOn = false;
}
Constructor
18
School of Information Technologies / The University of Sydney 2011-S2
Car class
…
public double getPosition(){
return position;
}
public void setPosition(double position) {
this.position = position;
}
…
public boolean isAcceleratorOn() {
return acceleratorOn;
}
public void setAcceleratorOn(boolean acceleratorOn) {
this.acceleratorOn = acceleratorOn;
}
Some getters and
setters
(generated by Eclipse)
School of Information Technologies / The University of Sydney 2011-S2
Examplepublic static double getLowerSpeedLimit() {return lowerSpeedLimit;
}
public static void setLowerSpeedLimit(double lowerSpeedLimit) {
Car.lowerSpeedLimit = lowerSpeedLimit;
}
…
public static double getFriction() {
return friction;
}
public static void setFriction(double friction) {
Car.friction = friction;
}
More getters and
setters
19
School of Information Technologies / The University of Sydney 2011-S2
Car class
public String toString(){
return name+": Pos="+position+"; Acc="+accelerationPower+
";Brake="+brakePower;
}
School of Information Technologies / The University of Sydney 2011-S2
Car class
public void drive(double time){
if (speedupperSpeedLimit){
brakeOn = true;
acceleratorOn = false;
}
double a = -friction;
if (acceleratorOn) a += accelerationPower;
if (brakeOn) a -= brakePower;
speed = speed + time*a;
position += time*speed;
}
Method drive() describes
the behaviour of a normal
driver:
• If the speed is lower than
the lower speed limit then
accelerate.
• If the speed exceeds the
upper speed limit, then
apply the brake.
• Otherwise keep the
status quo.
20
School of Information Technologies / The University of Sydney 2011-S2
public class Car {
private double speed;
private double accelerationPower;
private double brakePower;
private boolean acceleratorOn;
private boolean brakeOn;
private double position;
private String name;
private static double lowerSpeedLimit =
80.0;
private static double upperSpeedLimit =
110.0;
private static double friction = 0.3;
public Car(String n, double p, double a,
double b){
name = n;
position = p;
accelerationPower = a;
brakePower = b;
speed = 0.0;
acceleratorOn = true;
brakeOn = false;
}
public double getPosition(){
return position;
}
public double getSpeed(){
return speed;
}
public String getName(){
return name;
}
public double getAccelerationPower() {
return accelerationPower;
}
public void setAccelerationPower(double
accelerationPower) {
this.accelerationPower = accelerationPower;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public void setPosition(double position) {
this.position = position;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return name + ": Pos=" + position + "; Acc=" +
accelerationPower + "; Brake=" + brakePower;
}
public void drive(double time){
if (speedgetUpperSpeedLimit()){
brakeOn = true;
acceleratorOn = false;
}
double a = -friction;
if (acceleratorOn) a += accelerationPower;
if (brakeOn) a -= brakePower;
speed = speed + time*a;
position += time*speed;
}
public static double getFriction() {
return friction;
}
public static void setFriction(double friction) {
Car.friction = friction;
}
}
Complete
code for class
Car
public double getBrakePower() {
return brakePower;
}
public void setBrakePower(double brakePower){
this.brakePower = brakePower;
}
public boolean isAcceleratorOn() {
return acceleratorOn;
}
public void setAcceleratorOn(boolean
acceleratorOn) {
this.acceleratorOn = acceleratorOn;
}
public boolean isBrakeOn() {
return brakeOn;
}
public void setBrakeOn(boolean brakeOn) {
this.brakeOn = brakeOn;
}
public static double getLowerSpeedLimit() {
return lowerSpeedLimit;
}
public static void setLowerSpeedLimit(double
lowerSpeedLimit) {
Car.lowerSpeedLimit = lowerSpeedLimit;
}
public static double getUpperSpeedLimit() {
return upperSpeedLimit;
}
public static void setUpperSpeedLimit(double
upperSpeedLimit) {
Car.upperSpeedLimit = upperSpeedLimit;
}
School of Information Technologies / The University of Sydney 2011-S2
And now for slow drivers:
public class SlowCar extends Car {
public SlowCar(String n, double p, double a, double b){
super(n,p,a,b);
}
public void drive(double time){
if (getSpeed()speediness*getUpperSpeedLimit()){
setBrakeOn(true);
setAcceleratorOn(false);
}
else {
setBrakeOn(false);
setAcceleratorOn(true);
}
double a = -getFriction();
if (isAcceleratorOn()) a += getAccelerationPower();
if (isBrakeOn()) a -= getBrakePower();
setSpeed(getSpeed() + time*a);
setPosition(getPosition() + time*getSpeed());
}
}
Complete
code for
class
SpeedyCar
22
School of Information Technologies / The University of Sydney 2011-S2
And now for fast drivers:
…
private double speediness;
public SpeedyCar(String n, double p, double a, double b, double s){
super(n,p,a,b);
speediness = s;
}
…
School of Information Technologies / The University of Sydney 2011-S2
Drive for speedy drivers:
public void drive(double time){
if (getSpeed()>speediness*getUpperSpeedLimit()){
setBrakeOn(true);
setAcceleratorOn(false);
}
else {
setBrakeOn(false);
setAcceleratorOn(true);
}
double a = -getFriction();
if (isAcceleratorOn()) a += getAccelerationPower();
if (isBrakeOn()) a -= getBrakePower();
setSpeed(getSpeed() + time*a);
setPosition(getPosition() + time*getSpeed());
}
This method drive()
describes the
behaviour of a speedy
driver:
• If the speed is
greater than
speediness times
the upper speed
limit, then the
driver applies the
brake.
• Otherwise the
driver accelerates.
23
School of Information Technologies / The University of Sydney 2011-S2
CarTester:
public class CarTester {
public static void main(String[] args) {
Car c1 = new Car("Norman", 10, 1, 1);
Car c2 = new SpeedyCar("Zippy", 10, 1, 1, 1.3);
Car c3 = new SlowCar("Sleepy", 10, 1,1);
System.out.println(c3 + "\t" + c2 + "\t" + c1);
c1.drive(1);
c2.drive(1);
c3.drive(1);
System.out.println(c3 + "\t" + c2 + "\t" + c1);
}
}
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism via Inheritance
24
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism
Inheritance allows you to define a base class and derive
subclasses from the base class
Polymorphism allows you to make changes in the method
implementation for the subclasses and have those changes
achieved via the same method name as defined in the base class
This allows
Dynamic binding (also known as late binding)
Method overloading is an example of static polymorphism
(compile time), while method overriding is an example of
dynamic binding (runtime).
School of Information Technologies / The University of Sydney 2011-S2
Method calls are determined by type of actual object (using
new and constructor), not type of object reference
Polymorphism
In Java, type of a reference variable doesn't completely determine
type of object to which it refers.
Car c1 = new Car("Norman", 0, 1, 1);
Car c2 = new SpeedyCar("Zippy", 0, 1, 1, 1.3);
Car c3 = new SlowCar("Sleepy", 0, 1,1);
c1.drive(1);
c2.drive(1);
c3.drive(1);
This is an example of polymorphism: the ability to refer to
objects of multiple types with varying behaviors
25
School of Information Technologies / The University of Sydney 2011-S2
Polymorphism
In Java, type of a reference variable doesn't completely determine
type of object to which it refers.
Car c1 = new Car("Norman", 0, 1, 1);
c1.drive(1);
c1 = new SpeedyCar("Zippy", 0, 1, 1, 1.3);
c1.drive(1);
c1 = new SlowCar("Sleepy", 0, 1,1);
c1.drive(1);
This is an example of polymorphism: the ability to refer to
objects of multiple types with varying behaviors
SpeedyCar object
Name=“Zippy”
position = 0;
accelerationPower = 1;
brakePower = 1
Speediness =1.3
drive()
Car object
Name=“Norman”
position = 0;
accelerationPower = 1;
brakePower = 1
move()
drive()
Car object
Name=“Norman”
position = 0;
accelerationPower = 1;
brakePower = 1
move()
SlowCar object
Sleepy”
drive()
School of Information Technologies / The University of Sydney 2011-S2
Abstract Class
26
School of Information Technologies / The University of Sydney 2011-S2
Abstract methods and classes
An abstract method is a method without method body
Classes with abstract methods are abstract classes.
The concrete implementation of an abstract method is
specified in the subclasses
abstract Car
double speed;
… …
.abstract void drive
SlowCar
void drive
SpeedyCar
double speediness
void drive
NormalCar
void drive
School of Information Technologies / The University of Sydney 2011-S2
Abstract methods and classes
An abstract method is a method whose implementation is not specified
The concrete implementation of an abstract method is specified in the
subclasses
public abstract class Car {
//… …
//… ….
//… ….
public abstract void drive (double time);
}
Car class, version 2
Abstract
class
Abstract method:
No method body
27
School of Information Technologies / The University of Sydney 2011-S2
Abstract methods and classes
public class NormalCar extends Car {
…
public void drive(double time){
if (getSpeed()getUpperSpeedLimit()){
setBrakeOn(true);
setAcceleratorOn(false);
}
double a = -getFriction();
if (isAcceleratorOn()) a += getAccelerationPower();
if (isBrakeOn()) a -= getBrakePower();
setSpeed(getSpeed() + time*a);
setPosition(getPosition() + time*getSpeed());
}
}
NormalCar class
School of Information Technologies / The University of Sydney 2011-S2
Abstract methods and classes
A class that defines an abstract method, or that inherits an
abstract method without overriding it, must be declared as
abstract class.
An abstract class is to be EXTENDED
An abstract class cannot be instantiated.
You cannot construct objects from abstract classes.
28
School of Information Technologies / The University of Sydney 2011-S2
Final Class
School of Information Technologies / The University of Sydney 2011-S2
You can use the final keyword to prevent other programmers
from creating subclasses or from overriding certain methods.
For example, the String class in the standard Java library has been
declared as:
public final class String . . .
Thus nobody can extend the String class.
You can also declare individual methods as final:
public class SecureAccount extends BankAccount {
. . .
public final boolean checkPassword (String password)
{ . . . }
}
Final Classes and Methods
Nobody can override the checkPassword method
with another method that simply returns true
29
School of Information Technologies / The University of Sydney 2011-S2
Final Classes and Methods
final classes and methods
a final method can’t be over-ridden in a subclass
a final class can’t be extended at all
final methods are safer
final methods improve runtime efficiency, as there is no
need for late binding in this case.
School of Information Technologies / The University of Sydney 2011-S2
Comments on Quiz 2