Polymorphism in Java has two types:
- Compile time polymorphism (static binding)
Method overloading is an example of static polymorphism, Static Polymorphism: is achieved through
- method overloading. ie. there are several methods present in a class having the same name but different types/order/number of parameters.
class Calculator
{
public int add(int x, int y)
{ //method 1
return x+y;
}
public int add(int x, int y, int z)
{ //method 2
return x+y+z;
}
}
class Test{
public static void main(String[] args)
{
Calculator obj =new Calculator();
System.out.println(obj.add(2,3)); //method 1 called
System.out.println(obj.add(2,3,4)); //method 2 called\
}
}
- Operator Overloading: Java also provide option to overload operators.
“+” operator can be overloaded:
To add integers
int c = a + b;
To concatenate strings
String s = str1 + str2;
- Runtime polymorphism (dynamic binding). Method overriding is an example of dynamic polymorphism. It is a process in which a function call to the overridden method is resolved at Runtime.
It occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
class Parent
{
public void Print()
{
System.out.println(“Parent’s Print()”);
}
}
class Child extends Parent
{
public void Print()
{
System.out.println(“Child’s Print()”)
}
public class Main
{
public static void main(String[] args)
{
Parent p = new Parent();
p.Print();
Child c = new Child();
c.Print();
}
}