Chapter 5
July 2011
POLYMOPHISM
As introduced in previous notes (C4 & C5), we create an object of class as below:
This is correct and legal because a Cylinder object is also a Circle object.
This explains about polymorphism. The reference variable can refer to different type of
objects, as long as those types are its subclasses.
Page 1 of 6
as/5108/Tri47/C5p
Chapter 5
July 2011
Staff
Executive
PartTimer
Salesperson
Figure 5.2: A class hierarchy between Staff, Executive, PartTimer and Salesperson
class.
The following programs are to demonstrate the concept of overriding and polymorphism:
Staff is the superclass that defines basic info that a staff might has such name, id and
salary
Page 2 of 6
as/5108/Tri47/C5p
Chapter 5
July 2011
Page 3 of 6
as/5108/Tri47/C5p
Chapter 5
July 2011
Page 4 of 6
as/5108/Tri47/C5p
Chapter 5
July 2011
Explanations:
1) Program 5.9 demonstrates polymorphic behavior.
2) Refer to Line 5 - 9:
Dynamic Binding
Refer to Program 5.8 (Line 12): The program overrides the getSalary method.
Page 5 of 6
as/5108/Tri47/C5p
Chapter 5
July 2011
JVM determines at runtime which method to call, depending on the type of object
that the variables references.
AGGREGATION
Result
Student
Subject
Lecturer
Figure 5.3: UML diagram that shows the relationship among the Result, Student, Subject and
Lecturer classes.
Page 6 of 6
as/5108/Tri47/C5p