Polymorphism
Polymorphism
PROGRAMMING
POLYMORPHI
SM
3
Polymorphism
Poly Many
Morphs Forms
Polymorphism Many
forms
A person at the same time can have different characteristic.
Student and an employee.
So the same person posses different behavior in different situations.
In other words, polymorphism allows you to define one interface and have
multiple implementations.
This is called polymorphism.
4
Polymorphism
POLYMORPHISM TYPES
Runtime polymorphism is a process in which call to the overridden
method is resolved at Runtime (that means which overridden function
will run is decided at runtime).
.
USING SUPER TO ACCESS HIDDEN Members Functions OF
SUPERCLASS
class Parent
{
void show() / Driver class
{ class Main
System.out.println("Parent's {
show()"); public static void main(String[]
} args)
} {
/ Inherited class Child obj = new
class Child extends Parent Child(); obj.show();
{ }
/ This method overrides show() of }
Parent @Override
void show()
{
super.show(); 22
System.out.println("Child's
show()");
Summary
DYNAMIC METHOD DISPATCH
Important point
◾ Since a superclass reference variable can refer to a subclass
object, Java uses this fact to resolve calls to overridden methods at run
time.
◾ In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an
ASSIGNING OBJECT REFERENCE VARIABLES
◾ Object reference variables act differently when an assignment takes
place.
◾ Example:
◾ Box b1 = new Box();
◾ Box b2 = b1;
figref = r;
System.out.println("Area is " +
figref.area());
Inside Area for
figref = t; Rectangle. Area is
System.out.println("Area is " + 45.0
figref.area());
Inside Area for
Triangle. Area is
figref = f;
40.0
System.out.println("Area is " +
In Java, we can override methods only, not
the variables(data members), so runtime
polymorphism cannot be achieved by data
members.