The word polymorphism means having many forms. Polymorphism is one of the most important features of Object-Oriented Programming. Polymorphism allows us to perform a single task in different ways. In other words, it allows us to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So polymorphism means many forms.
1. Compile-time polymorphism: It is also known as static polymorphism. This type of polymorphism is achieved by operator overloading or function overloading. But java support function overloading not Operator Overloading.
Method Overloading: Writing two or more methods in the same class in such a way that each method has same name but change in number of arguments or/and change in type of arguments is called method overloading.
// Java program for Method overloading
class OverloadingClass {
// Method with 2 parameter
static int multiply(int a, int b)
{
return a * b;
}
// Method with the same name but 3 parameter
static int multiply(int a, int b, int c)
{
return a * b * c;
}
}
class Simple {
public static void main(String[] args)
{
OverloadingClass obj = new OverloadingClass();
System.out.println(obj.multiply(4, 1));
System.out.println(obj.multiply(4, 2, 3));
}
}
Output:
4
24
// Java program for Method overloading
class OverloadingClass {
// Method with 2 parameter
static int multiply(int a, int b)
{
return a * b;
}
// Method with the same name but 2 double parameter
static double multiply(double a, double b)
{
return a * b;
}
}
class Simple {
public static void main(String[] args)
{
OverloadingClass obj = new OverloadingClass();
System.out.println(obj.multiply(3, 4));
System.out.println(obj.multiply(2.5, 3.3));
}
}
Output:
12
8.25
2. Runtime polymorphism: Runtime polymorphism in java is also known as Dynamic Binding or Dynamic Method Dispatch. In this process, the call to an overridden method is resolved dynamically at runtime rather than at compile-time. Runtime polymorphism is achieved through Method Overriding.
Method overriding: Writing two or more method with the same name and same signature is called method overriding. Method overriding is achived by inheritance. When a super class method is overridden by the sub class method , JVM calls only the sub class method and never the super class method that means we can say that the sub class method is replacing the super class method.
class Phone{
void run()
{
System.out.println("Phone");
}
}
class SmartPhone extends Phone{
void run()
{
System.out.println("SmartPhone");
}
public static void main(String args[]){
Phone p = new SmartPhone();
p.run();
}
}
Output:
SmartPhone
class Sum
{
void sum(int a)
{
System.out.println("Area is "+(a*a));
}
}
class Sum2 extends Sum
{
void sum(int a)
{
System.out.println("Area is "+Math.sqrt(a));
}
}
class Overriding
{
public static void main(String []args)
{
Sum2 obj = new Sum2();
obj.sum(9);
}
}
Output:
Area is 3.0