Polymorphism in Java

The word polymorphism means having many forms. In simple words,

Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person possess different behavior in different situations. This is called polymorphism.

Example

public class Animal{

  

   public void sound(){

      System.out.println(“Animal is making a sound”);  

   }

}

Now let’s say we two subclasses of Animal classHorse and Cat that extends (like InheritanceAnimal class. We can provide the implementation to the same method like this:

public class Horse extends Animal{
...
    @Override
    public void sound(){
        System.out.println("Neigh");
    }
}                                                    

and

public class Cat extends Animal{
...
    @Override
    public void sound(){
        System.out.println("Meow");
    }
}

We had the common action for all subclasses sound() Because of Animal class we get
sound() method in Horse and Cat,
This is a perfect example of polymorphism, see the difference horse Neigh and cat Meow, each Animal has a different sound

There are two types of polymorphism in java:

1) Static Polymorphism also known as compile time polymorphism

2) Dynamic Polymorphism also known as runtime polymorphism

Compile time Polymorphism (or Static polymorphism)

Polymorphism that is checked in compile time is known as static polymorphism

Method overloading is an example of compile time polymorphism.

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading in java.

class SimpleCalculator

{
    int add(int a, int b)
    {
         return a+b;
    }
    int  add(int a, int b, int c)  
    {
         return a+b+c;
    }
}
public class Demo
{
   public static void main(String args[])
   {
                       SimpleCalculator obj = new SimpleCalculator();
       System.out.println(obj.add(10, 20));
       System.out.println(obj.add(10, 20, 30));
   }
}

Results

30
60

Runtime Polymorphism (or Dynamic polymorphism) 

class Employee{
   public void profile(){
                    System.out.println("Employee");
   }
}
public class Contract extends Employee {
 
   public void profile(){
                    System.out.println("Employee of Contract");
   }
}
public class Part_Time extends Employee {
   public void profile(){
                    System.out.println("Employee of Partime");
   }
}

It is also known as late binding or Dynamic binding.

In the above example while compile time s.draw() point to shape class.

In the above example while compile time s.draw() point to shape class. Java training courses are clearly educate for java concepts.

 

Spread the love