What is polymorphism in java?
Polymorphism is one of the OOPs features that allow us to perform a single action in different ways. For example, let’s say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it an implementation like Roar, Meow, Oink etc. We had to give a generic message.
public class Animal{
...
public void sound(){
System.out.println(""Animal is making a sound"");
}
}
Now lets say we two subclasses of Animal class: Horse and Cat that extends (see Inheritance) Animal 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"");
}
}
As you can see that although we had the common action for all subclasses sound() but there were different ways to do the same action. This is a perfect example of polymorphism (feature that allows us to perform a single action in different ways). It would not make any sense to just call the generic sound() method as each Animal has a different sound. Thus we can say that the action this method performs is based on the type of object."