OBJECT ORIENTED
PROGRAMMING
Topic 7:
Polymorphism
TOPIC COVERED
Polymorphism concept
Abstract classes and methods
Method overriding
Concrete sub classes and methods
POLYMORPHISM CONCEPT
Polymorphism means “having many
forms”
It is the ability to use the same name to
refer to methods that perform different
tasks
Ability of a variable to have more than one
type – hold values of different types.
POLYMORPHISM CONCEPT
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
To expand the usage and the
effectiveness of polymorphism,
we have to apply the concept
of abstract class and the
array
POLYMORPHISM
PART 1
ABSTRACT
CLASS
ABSTRACT CLASS
An abstract class is a common solution when we know
the subclass is likely to override the superclass.
Main reason :-
To avoid redundant codes
Several concrete classes have some common code that can be
implemented in a single superclass.
A class is declared as abstract by including the
keyword abstract in the class’s header line :
public abstract class student { ….. }
ABSTRACT CLASS
VS
CONCRETE CLASS
ABSTRACT CLASS VS CONCRETE CLASS
Similar to a concrete class :-
➢ Has either public, protected, private or package
accessibility
➢ May include constructors
➢ May include methods, classes and interfaces
Difference to a concrete class :-
➢ May contain abstract method
➢ Cannot be instantiated
ABSTRACT CLASSES
Student
{abstract}
+NUM_OF_TEST = 2
#name
#test1
#test2
+ Student()
+ Student(String, int, int)
+ getName() : String
+ getTestScore1() : int
+ getTestScore2() : int
+ setName(String) : void
+ setTestScore(int,int) : void
UndergraduateStudent GraduateStudent
Sibling
+UndergraduateStudent (String,
Classes +GaduateStudent (String, int,
int, int) int)
13
ABSTRACT
METHODS
ABSTRACT CLASSES AND METHODS
For example,
public abstract class Student
{
…….
abstract public void displayCourseGrade();
abstract public double calcCGPA();
}
16
ABSTRACT CLASSES AND METHODS
EXAMPLE
Student
{abstract}
+NUM_OF_TEST = 2
#name
#test1
#test2
+ Student()
+ Student(String, int, int)
+ getName() : String
+ getTestScore1() : int
+ getTestScore2() : int
+ setName(String) : void
+ setTestScore(int,int) : void
+ displayCourseGrade() : void {abstract}
UndergraduateStudent GraduateStudent
Sibling
+UndergraduateStudent (String,
Classes +GaduateStudent (String, int,
int, int) int)
+ displayCourseGrade() : void + displayCourseGrade () : void
17
METHOD
OVERRIDING
METHOD OVERRIDING
The overriding method must have the same
name, same arguments and same return type
as the overridden method.
Generally to override the abstract method.
Can occur in two different forms :-
Replacement
A method can replace the method in parent class. Code in
parent class is not executed at all.
Refinement
Combines the code from parent and child class – the use of
keyword super (constructor)
ABSTRACT CLASSES AND METHODS
EXAMPLE
public abstract class Card {
protected String recipient;
public Card (String r)
{ recipient = r; }
public abstract void greeting(); class HariRaya extends Card {
} //end Card public HariRaya(String r)
{ super(r); }
-----------------------------------------------------
public void greeting()
class Birthday extends Card { { System.out.println(“Dear “ +
private String date; super.recipient + “ , \n Selamat Hari
Raya”); }
public Birthday(String r, String d)
{ super(r); date =d; } }//end HariRaya
public void greeting()
{ System.out.println(“Dear “ +
super.recipient + “ , \n Happy
Birthday ” + date); }
} //end Birthday
TEST YOURSELF
TEST YOURSELF
1. Define an abstract Actor class with abstract
method caclAllowanceReceived().
2. Override the method
caclAllowanceReceived() in the subclasses
PartTimeActor and FullTimeActor – USING
PREVIOUS CALCULATION.
POLYMORPHISM
PART 2
DYNAMIC
BINDING
DYNAMIC BINDING
You can indirectly create a reference to a superclass abstract
object.
A reference is not an object but it points to a memory address
– create variable name that hold the memory address of a
concrete object.
Whenever you code
CLASSNAME objectName;
you are created a reference to object, then you code
objectName = new CLASSNAME;
you actually set aside memory for the objectName
DYNAMIC BINDING EXAMPLE
Animal
{abstract}
#ownerName : String
+ Animal(String)
+ speak() : void {abstract}
Cow Cat
+Cow(String) +Cat(String)
+ speak() : void + speak() : void
DYNAMIC BINDING EXAMPLE
public class AnimalApp
{ ****The variable ref is a
public static void main (String args[]) type of Animal, but no
superclass Animal object
{
is created, instead Cat
Animal ref;
and Cow objects are
created using the keyword
ref = new Cow(“Abu”); new.
ref.speak();
ref = new Cat(“Ali”);
ref.speak()
}
}
ARRAY IN
POLYMORPHISM
ARRAY IN POLYMORPHISM
Similar to implement the array in the
inheritance concept. But we want the reference of
array which is comes from the parent class.
You might want to create a superclass reference
and treat subclass objects as superclass objects so
you can create an array of different objects that
share the same ancestry.
Manipulate an array of subclass objects by
invoking the appropriate method for each
subclass.
ARRAY IN POLYMORPHISM EXAMPLE
class HariRaya extends Card {
public HariRaya(String r)
{ super(r); }
public abstract class Card {
private String recipient; public void greeting()
{ System.out.println(“Dear “ +
public Card (String r) super.recipient + “ , \n Selamat Hari
{ recipient = r; } Raya”); }
public abstract void greeting(); }//end HariRaya
} //end Card
The application class :
class Birthday extends Card {
private String date; class CardApp {
public static void main(String[] args) {
public Birthday(String r, String d) Card c [] = new Card [2];
{ super(r); date =d; } c[0] = new Birthday(“Rashid”, “2/3/2013”);
c[1]= new HariRaya(“Siti”);
public void greeting() c[0].greeting();
{ System.out.println(“Dear “ + c[1].greeting();
super.recipient + “ , \n Happy }
Birthday ” + date); } } //end CardApp
} //end Birthday
ARRAY IN POLYMORPHISM
The application class :
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”);
c[0].greeting();
c[1].greeting();
}
} //end CardApp
ARRAY IN POLYMORPHISM
From the previous slide example – CardsApp
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”);
for (int j = 0; j <2; j++)
{ c[j].greeting(); }
} //end CardApp
ARRAY OF
SUPERCLASS
ARRAY OF SUPERCLASS
Array of different objects that share the same
superclass.
The objects in the array has access to the same
method of the superclass.
ARRAY OF SUPERCLASS
Can be declared to hold objects of different
subclasses.
35
Before creating the object, ask
the user what type of object to
be created!
EXAMPLE :
public class AnimalArray
{
public static void main(String args[])
{
Animal[] ref = new Animal[2];
ref[0] = new Cow(“Abu”);
ref[1] = new Cat(“Ali”);
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];
for (int i=0; i<2; i++) {
System.out.print(“Animal type:[ cow / cat] : ");
String type = in.next();
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
1. Define an application class to
Create 10 objects of Actor and store the data
into the objects.
Let the user decide subclasses instantiation
type for the 10 actors.
Find each actor’s payment.
POLYMORPHISM
PART 3
OPERATOR
INSTANCEOF
OPERATOR INSTANCEOF
Is used to determine the class of an object (which
subclass is currently point by object reference of
superclass) – filter after creating (instantiation
/new)
Example
Card c = new Birthday();
if( c instanceof Birthday )
{ System.out.println(“C is a Birthday Card”); }
else
{ System.out.println(“C is other Card”); }
OPERATOR INSTANCEOF (OUTPUT)
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”);
for (int i=0; i<2; i++)
if( c[i] instanceof Birthday )
c[i].greeting();
}
}
CASTING
CASTING
Casting is taking an Object of one particular type
and “turning it into” another Object type.
To ensure the certain methods can be used
through sub-class definition.
*** Used when there is/are extra method(s) in the
certain subclass.
WITHOUT CASTING
class HariRaya extends Card {
public HariRaya(String r)
{ super(r); }
public abstract class Card {
protected String recipient; public void greeting()
{ System.out.println(“Dear “ +
public Card (String r) super.recipient + “ , \n Selamat Hari
{ recipient = r; } Raya”); }
public abstract void greeting(); }//end HariRaya
} //end Card
The application class :
class Birthday extends Card {
private String date; class CardApp {
public static void main(String[] args) {
public Birthday(String r, String d) Card c [] = new Card [2];
{ super(r); date =d; } c[0] = new Birthday(“Rashid”, “2/3/2013”);
c[1]= new HariRaya(“Siti”);
public void greeting()
{ System.out.println(“Dear “ + for (int j = 0; j <2; j++)
super.recipient + “ , \n Happy c[j].greeting();
Birthday ” + date); } }
} //end Birthday } //end CardApp
CASTING EXAMPLE
public abstract class Card {
protected String recipient;
public Card (String r)
{ recipient = r; }
public abstract void greeting();
} //end Card
class Birthday extends Card {
private String date;
public Birthday(String r, String d)
{ super(r); date =d; }
public void greeting()
{ System.out.println(“Dear “ + super.recipient + “ , \n Happy Birthday ” + date); }
public void partyDate()
{ System.out.println(“Date of the party:” + date); }
} //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.
2. Define an application class to create 10 objects
of Actor to :
a) Input data into the subclasses.
b) Find each full time actor’s payment.
c) Find the maximum overtime received by the part
time actors.
d) Find the average allowance received by all actors.
END.
Thank you.