Lecture_07_Polymorphism
Lecture_07_Polymorphism
Polymorphism
CSIT213 Java Programming
Overview
• Polymorphism
• Operator instanceof
• Class downcasting
2
Introduction
• Polymorphism enables a developer to write a program in the general
rather than specific.
3
Polymorphism
playback any stream
a virtual object
playbackStream
StreamPlayer
(arg)
4
Advantages
• With polymorphism, we can design and implement easily extensible systems.
5
Class inheritance hierarchy
6
testEmployee.java
Different implementations
class Employee { class Tech extends Employee {
private int number; private String speciality;
private String name; …
private String address; public String toString() {
… return String.format("%s\nSpeciality: %s",
public String toString() { super.toString(), speciality);
return String.format("Number: }
%d\nName: %s\nAddress: %s", number, name, }
address);
}
}
Employee e = new Admin(12345, "Alice", "1 Northfields ave Wollongong", "read write",
85000.5);
emps.add(e);
e = new Contractor(22345, "Bob", "1 Ocean road Wollongong", "Java C++", "1/1/2020",
"31/12/2022", 95000.5);
emps.add(e);
e = new Admin(32345, "Kate", "1 Moore street Wollongong", "read write", 85000.5);
emps.add(e);
e = new Casual(42345, "Peter", "1 Cliff street Wollongong", "Python Java C++", 72.5, 35);
emps.add(e);
for(Employee v:emps)
System.out.println(v.toString());
8
Polymorphic behaviour
• An object of a subclass can be treated as an object of its superclass,
enabling various interesting manipulations.
• A program can create a collector of superclass variable that refers to
objects of many subclass types.
• In the example, a superclass reference at a subclass object.
- Invoking a method on a subclass object via a superclass reference
invokes the subclass functionality
- At execution time, the type of the referenced object (subclass), NOT
the type of the variable (superclass), determines which method is
called.
• This process is called dynamic binding (late binding).
9
Methods are defined in subclasses
10
testEmployee3.java
11
Downcasting
• A superclass object cannot be treated as a subclass object, because a
superclass object is not an object of any of its subclasses.
• The is-a relationship applies only up the hierarchy from a subclass to its direct
(and indirect) superclasses, and not down the hierarchy.
12
testEmployee4.java
13
getClass() and getName()
• Every object knows its own class and can access this information
through the getClass() method, which all classes inherit from class
Object.
• The getClass() method returns an object of type Class (from package
java.lang), which contains information about the object’s type,
including its class name.
• The result of the getClass() call is used to invoke getName() to get the
object’s class name.
Example:
for(Emploee v:emps)
System.out.println("class: " + v.getClass() + ", name: " +
v.getClass().getName());
14
Abstract classes and methods
• You make a class abstract by declaring it with the keyword abstract ClassName.
• An abstract class normally contains one or more abstract methods.
An abstract method is an instance method with the keyword abstract in its
declaration, as in
public abstract void draw();
In the UML class diagram, the italic font is used for abstract classes and
methods
• Abstract methods do not provide implementations (the method body).
• A class that contains abstract methods must be abstract even if that class
contains some concrete (non-abstract) methods because it is incomplete.
• Each concrete subclass of an abstract superclass also must provide concrete
implementations of each of the superclass’s abstract methods.
• Constructors and static methods cannot be declared abstract.
15
UML class hierarchy
Abstract class
Abstract method
16
testEmployee5.java
Example - Employee
abstract class Employee { Abstract class
private int number;
private String name;
private String address;
17
Example - Admin
class Admin extends Employee { Concrete class
private String skills;
private double salary;
public Admin(int number, String name, String address, String skills, double salary) {
super(number, name, address);
this.skills = skills;
this.salary = salary;
}
@Override
public double earning() { Must override the abstract method
return salary;
}
@Override
public String toString() {
return String.format("%s\nSkills: %s", super.toString(), skills);
}
}
18
Example - Tech
abstract class Tech extends Employee { Abstract class
private String speciality;
19
Example - Contractor
class Contractor extends Tech { Concrete class
private String startDate;
private String endDate;
private double salary;
…
public double earning() { Must override the abstract method
return salary;
}
20
Example - Casual
class Casual extends Tech { Concrete class
private double hourlyRate;
private double hours;
public Casual(int number, String name, String address, String spec, double hr,
double h) {
super(number, name, address, spec);
hourlyRate = hr;
hours = h;
}
for(Employee v:emps) {
System.out.println("Class name: " + v.getClass().getName());
System.out.println(v.toString() + "\nEarning: " + v.earning());
System.out.println();
}
Call override methods
22
Abstract classes and static methods
• You cannot instantiate objects of abstract superclasses, but you can use
abstract superclasses to declare variables.
23
Final methods
• A final method in a superclass cannot be overridden in a subclass.
- Methods that are declared private are implicitly final because it’s not
possible to override them in a subclass.
24
testEmployee6.java
25
Example –toString() in a subclass
class Admin extends Employee {
private String skills;
private double salary;
…
@Override
public double earning() { Error: Cannot
return salary;
override
toString()
}
@Override
public String toString() {
return String.format("%s\nSkills: %s", super.toString(), skills);
}
}
26
Final class
27
Example – a final class Contractor
final class Contractor extends Tech { A final class Contractor
private String startDate;
private String endDate;
private double salary;
…
public double earning() {
return salary;
}
28
Example – a subclass Parttime
class PartTime extends Contractor {
private double percentage;
… Error: Cannot
public double earning() { inherit from
return super.earning() * percentage / 100.0; final Contractor
}
29
Final class String
• Class String is an example of a final class.
- Since class String cannot be extended, programs that use Strings can
rely on the functionality of String objects as specified in the Java API.
30
Summary
• There are 3 proper ways to assign superclass and subclass references to
variables of superclass and subclass types.
- Assigning a superclass reference (variable) to a superclass object is
straightforward.
- Assigning a subclass reference (variable) to a subclass object (same
type) is straightforward.
- Assigning a superclass reference (variable) to a subclass object is safe
because the subclass object is an object of its superclass.
• The superclass reference (variable) can be used to refer only to superclass
members.
• If this code refers to subclass-only members through the superclass
reference (variable), the compiler reports errors. Then the class
downcasting shall be used to resolve the errors.
• Sometimes, if the override methods defined in a particular subclass shall
be called, the class downcasting shall also be used.
31