0% found this document useful (0 votes)
8 views

Lecture_07_Polymorphism

The document provides an overview of polymorphism in Java, discussing its importance in enabling general programming and dynamic binding at runtime. It covers concepts such as abstract classes, downcasting, the use of the 'instanceof' operator, and the implications of final methods and classes. The document illustrates these concepts with examples of class hierarchies and method implementations.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture_07_Polymorphism

The document provides an overview of polymorphism in Java, discussing its importance in enabling general programming and dynamic binding at runtime. It covers concepts such as abstract classes, downcasting, the use of the 'instanceof' operator, and the implications of final methods and classes. The document illustrates these concepts with examples of class hierarchies and method implementations.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Java

Polymorphism
CSIT213 Java Programming
Overview
• Polymorphism

• Abstract classes and methods

• Operator instanceof

• Class downcasting

• The final methods and classes

2
Introduction
• Polymorphism enables a developer to write a program in the general
rather than specific.

• Polymorphism enables programs share the same superclass as they


are all the objects of the superclass.

• Polymorphism makes the program simple.

3
Polymorphism
playback any stream
a virtual object
playbackStream
StreamPlayer
(arg)

mp3 Player mpeg4 mpeg2


Player Player

• Polymorphism leads to generic implementations.


• Binding to the right objects is carried out dynamically at run-time.
• Polymorphism is one of the most powerful OOD concepts supported
by Java programming language.

4
Advantages
• With polymorphism, we can design and implement easily extensible systems.

• New classes can be added with little or no modification to the general


portions of the program, as long as the new classes are part of the inheritance
hierarchy that the program processes generically.

- The new classes simply “plug right in”.

- The only parts of a program that must be altered to accommodate new


classes are those that require direct knowledge of the new classes (usually
are the extra fields defined in the sub-class) that we add to the hierarchy.

5
Class inheritance hierarchy

Same method names

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

class Contractor extends Tech { class Casual extends Tech {


private String startDate; private double hourlyRate;
private String endDate; private double hours;
private double salary; …
… public String toString() {
public String toString() { return String.format("%s\nHourly rate:
return String.format("%s\nStart %.2f\nHours: %.2f\nPayment: %.2f", super.toString(),
date: %s\nEnd date: %s\nSalary: %.2f", hourlyRate, hours, getPayment());
super.toString(), startDate, endDate, }
salary); }
}
}
7
Superclass references
ArrayList<Employee> emps = new ArrayList<Employee>();

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

Methods are available in


some subclasses only

10
testEmployee3.java

Call subclass methods


ArrayList<Employee> emps = new ArrayList<Employee>();

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); Defined in superclasses
and subclasses Compilation
for(Employee v:emps) { errors
System.out.println(v.toString());
System.out.println("Salary: " + v.getSalary());
System.out.println("Payment: " + v.getPayment()); Only defined in subclasses
}

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.

• The Java compiler does allow the assignment of a superclass reference to a


subclass variable if you explicitly cast the superclass reference to the
subclass type

• A technique is known as downcasting enables a program to invoke


subclass methods that are not in the superclass.

12
testEmployee4.java

instanceof and downcasting


A program can use the command instanceof to determine the type of an
object, then explicitly cast the superclass referenced object to a suitable
subclass object. This is called a downcasting.

for(Employee v:emps) { Determine the types of objects


if(v instanceof Admin)
System.out.printf("Admin salary: %.2f\n", ((Admin)v).getSalary());
else if(v instanceof Contractor)
System.out.printf("Contractor salary: %.2f\n", ((Contractor)v).getSalary());
else if(v instanceof Casual)
System.out.printf("Casual payment: %.2f\n", ((Casual)v).getPayment());
else
System.out.println("A super class. No salary or payment.");
}

Downcasting to subclass objects

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;

public Employee(int number, String name, String address) {


this.number = number;
this.name = name;
this.address = address;
}

public abstract double earning(); Abstract method
}

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;

public Tech(int number, String name, String address, String spec) {


super(number, name, address);
speciality = spec;
}

public String toString() {


return String.format("%s\nSpeciality: %s", super.toString(), speciality);
}

//No implementation of earning() No override the abstract method


}

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

public String toString() {


return String.format("%s\nStart date: %s\nEnd date: %s", super.toString(),
startDate, endDate);
}
}

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

public double earning() { Must override the abstract method


return hourlyRate * hours;
}

public String toString() {


return String.format("%s\nHourly rate: %.2f\nHours: %.2f", super.toString(),
hourlyRate, hours);
}
}
21
Example – tests
ArrayList<Employee> emps = new ArrayList<Employee>(); A collector of Employee

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("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.

- These can hold references to objects of any concrete subclass

derived from those abstract superclasses.

- We’ll use such variables to manipulate subclass objects polymorphically.

• Can use abstract superclass names to invoke static methods declared in


those abstract super classes.

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.

- Methods that are declared static are implicitly final.

- A final method’s declaration can never change, so all subclasses use


the same method implementation, and calls to final methods are
resolved at compile time—this is known as static binding.

24
testEmployee6.java

Example – final method in a superclass


abstract class Employee {
private int number;
private String name;
private String address;

public int getNumber() {
return number;
} A final method toString()

public final String toString() {


return String.format("Number: %d\nName: %s\nAddress: %s", number, name, address);
}

public abstract double earning();


}

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

• A final class cannot be extended to create a subclass. All methods


in a final class are implicitly final.

• Making the class final prevents programmers from creating


subclasses that might bypass security restrictions.

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

public String toString() {


return String.format("%s\nStart date: %s\nEnd date: %s", super.toString(),
startDate, endDate);
}
}

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
}

public String toString() {


return String.format("%s\nPercentage: %.2f", super.toString(), percentage);
}
}

29
Final class String
• Class String is an example of a final class.

- If you were allowed to create a subclass of String, objects of that


subclass could be used wherever Strings are expected.

- Since class String cannot be extended, programs that use Strings can
rely on the functionality of String objects as specified in the Java API.

- A String object is immutable. You are not allowed to modify a String


object. When you modify a String object, the compiler creates a clone
of the String object and the modification is applied on the cloned
copy, and the original String object will be automatically deleted from
the memory.

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

You might also like