18-05-2012, 04:29 PM
Polymorphism
javapolymorphism.pdf (Size: 197.27 KB / Downloads: 439)
What is Polymorphism?
● Generally, polymorphism refers to the ability to
appear in many forms
● Polymorphism in a Java program
– The ability of a reference variable to change
behavior according to what object instance it is
holding.
– This allows multiple objects of different subclasses
to be treated as objects of a single super class,
while automatically selecting the proper methods to
apply to a particular object based on the subclass it
belongs to
Polymorphism Example
● For example, given a base class shape,
polymorphism enables the programmer to define
different area methods for any number of derived
classes, such as circles, rectangles and triangles.
No matter what shape an object is, applying the
area method to it will return the correct results.
Benefits of Polymorphism
● Simplicity
– If you need to write code that deals with a family of types,
the code can ignore type-specific details and just interact
with the base type of the family
– Even though the code thinks it is using an object of the
base class, the object's class could actually be the base
class or any one of its subclasses
– This makes your code easier for you to write and easier
for others to understand