Polymorphism in Java is a concept by which we can perform a
single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many
forms.
In java language, polymorphism is essentially considered into two versions.
- Compile time polymorphism (static binding or method overloading)
- Runtime polymorphism (dynamic binding or method overriding)
Compile Time Polymorphism (static binding or method overloading)
As the meaning is implicit, this is used to write the program in such a way, that
flow of control is decided in compile time itself. It is
achieved using method overloading.
In
method overloading, an object can have two or more methods with same
name, BUT, with their method parameters different. These parameters may
be different on two bases:
Parameters type
Type of method parameters can be different. e.g.
java.util.Math.max()
function comes with following versions:
public static double Math.max( double a, double b){..}
public static float Math.max( float a, float b){..}
public static int Math.max( int a, int b){..}
public static long Math.max( long a, long b){..}
|
The actual method to be called is decided on compile time based on parameters passed to function in program.
Parameters count
Functions accepting different number of parameters. e.g. in employee management application, a factory can have these methods:
EmployeeFactory.create(String firstName, String lastName){...}
EmployeeFactory.create(Integer id, String firstName, String lastName){...}
|
Both methods have same name “create” but actual method invoked will be based on parameters passed in program.
Runtime Polymorphism (dynamic binding or method overriding)
Runtime polymorphism is essentially referred as method overriding. Method overriding is a feature which you get when you implement inheritance in your program.
A simple example can be from real world e.g. animals. An application can have
Animal
class, and its specialized sub classes like
Cat
and
Dog
. These subclasses will override the default behavior provided by
Animal
class + some of its own specific behavior.
public class Animal {
public void makeNoise()
{
System.out.println( "Some sound" );
}
}
class Dog extends Animal{
public void makeNoise()
{
System.out.println( "Bark" );
}
}
class Cat extends Animal{
public void makeNoise()
{
System.out.println( "Meawoo" );
}
}
|
Now which
makeNoise()
method will be called, depends on type of actual instance created on runtime e.g.
public
class
Demo
{
public
static
void
main(String[] args) {
Animal a1 =
new
Cat();
a1.makeNoise();
Animal a2 =
new
Dog();
a2.makeNoise();
}
}