7) Polymorphism
7) Polymorphism
PROGRAMMING
Topic 7:
Polymorphism
TOPIC COVERED
Polymorphism concept
Abstract classes and methods
Method overriding
Advantages :-
➢ Allows different (but related) objects the flexibility
to respond differently to the same message.
➢ Allow objects to treat other objects in a general
way.
➢ Code sharing
Disadvantages :-
➢ When you use it, you must treat different objects in
a general way
➢ Just by looking at the source code, it is not possible
to determine which code is executed.
POLYMORPHISM CONCEPT
Main reason :-
To avoid redundant codes
Several concrete classes have some common code that can be
implemented in a single superclass.
UndergraduateStudent GraduateStudent
Sibling
+UndergraduateStudent (String,
Classes +GaduateStudent (String, int,
int, int) int)
13
ABSTRACT
METHODS
ABSTRACT CLASSES AND METHODS
For example,
UndergraduateStudent GraduateStudent
Sibling
+UndergraduateStudent (String,
Classes +GaduateStudent (String, int,
int, int) int)
+ displayCourseGrade() : void + displayCourseGrade () : void
17
METHOD
OVERRIDING
METHOD OVERRIDING
Animal
{abstract}
#ownerName : String
+ Animal(String)
+ speak() : void {abstract}
Cow Cat
+Cow(String) +Cat(String)
+ speak() : void + speak() : void
DYNAMIC BINDING EXAMPLE
class CardApp
{
public static void main(String[] args)
{
Card c [] = new Card [2];
c[0].greeting();
c[1].greeting();
}
} //end CardApp
ARRAY IN POLYMORPHISM
class CardApp
{
public static void main(String[] args)
{
} //end CardApp
ARRAY OF
SUPERCLASS
ARRAY OF SUPERCLASS
35
Before creating the object, ask
the user what type of object to
be created!
EXAMPLE :
ref[0].speak();
ref[1].speak();
}
}
EXAMPLE (INPUT) :
public class AnimalArray {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
Animal[] ref = new Animal[2];
if (type.equals.(“cow”) ) {
ref[i] = new Cow(“Abu”);
}
else if (type.equals.(“cat”) ) {
ref[i] = new Cat(“Ali”);
}
}
for (int i=0; i<2; i++) {
ref[i] .speak();
}
}
}
TEST YOURSELF
TEST YOURSELF
Example
class CardApp
{
public static void main(String[] args)
{
Card c [] = new Card [2];
c [0] = new Birthday(“Rashid”, “2/3/2013”);
c [1]= new HariRaya(“Siti”);
} //end Birthday
CASTING EXAMPLE
//Application class
.
.
.
for (int i=0; i<2; i++)
{
//instanceof (filter)
if( c[i] instanceof Birthday )
{
//casting
Birthday tempB = (Birthday) c[i] ;
tempB. partyDate();
}
}
TEST YOURSELF
TEST YOURSELF
1. Add a new method to PartTime Actor named
calcOvertimeReceived() by return the
overtime receive if hour works more than
8 hour with payment RM10.00 per hour.