Chapter 5-Polymorphism
Chapter 5-Polymorphism
2
Polymorphism
Polymorphism is a Greek word meaning “many
forms”.
Polymorphism enables us to “program in the general”
rather than “program in the specific.”
Example: Suppose we create a program that
simulates the movement of several types of animals
for a biological study.
Classes Fish, Frog and Bird represent the three types of
animals under investigation.
Imagine that each of these classes extends superclass
Animal, which contains a method move and maintains an
animal’s current location as x-y coordinates.
3
Polymorphism(cont’d)
To simulate the animals’ movements, the program sends each
object the same message once per second.
However, each specific type of Animal responds to a move
message in a unique way
a Fish might swim three feet, a Frog might jump five feet and a
Bird might fly ten feet.
The program issues the same message (i.e., move ) to each
animal object generically, but each object knows how to
modify its x-y coordinates appropriately for its specific type
of movement.
4
Polymorphism(cont’d)
E.g. 2 One person present in different behaviors:
Suppose if you are in class room that time you behave like a student,
when you are in market at that time you behave like a customer,
when you at your home at that time you behave like a son or
daughter.
}
7
}
Example(cont’d)
Output
I’m Your cuddly little pet
Don’t give me orders
I speak only when I want