Polymorphism means the ability to take more than one form. For example, an operation may exhibit different behaviors in different instructions. In Java, polymorphism is supported through
i) Overloading: – often referred to as a compiler-time or static polymorphism or Early Binding, or Static binding.
ii) Overriding: – often referred to as a run-time or dynamic polymorphism, or lade binding or dynamic binding.
Method overloading: In Method overloading, Methods name is must be the same, but have different Signature, different return type as well as different behaviors in the same class.
Example:
class abc {
int a,b;
double c,d;
void add()
{
System.out.println(“No parameter”);
}
void add(int r,int s)
{
a=r;
b=s;
int n=a+b;
System.out.println(“int + int=”+n);
}
void add(double r,double s)
{
c=r;
d=s;
double n=c+d;
System.out.println(“double+double=”+n);
}
double add(int r,int s,double t)
{
a=r;
b=s;
c=t;
System.out.println(a+b+c);
return (a+b+c);
}
}
Method overriding: Writing two or more method in super and sub classes such that the methods have same name and same signature but different behavior is called method overriding in different class.
Example:
class A {
int c,d;
void input() {
c=20;
d=20;
}
void show()
{
System.out.println(c+d);
System.out.println(“Parent Class”);
}
}
class B extends A {
int a,b;
void input()
{
a=10;
b=20;
}
void show() {
System.out.println(c+d);
System.out.println(a+b);
System.out.println(“Child class”);
}
}