Hello fellow coders, I am back with another article in our Java OOP concepts article series. We learned about Inheritance in the earlier article. Today, we are going to learn about a concept called polymorphism that is also associated with Inheritance.
What is Polymorphism?
The word Polymorphism means many different forms.
Polymorphism can be implemented in Java in two ways.
1. Method Overriding (Runtime / Dynamic Polymorphism)
When there is a child class and a parent class, the child class can override the methods that are there in the parent class.
Here is a code snippet that shows how the concept can be implemented in Java code.
Animal Class (Parent Class)
public class Animal { public void speak(){ System.out.println("Animals speak"); } }
Dog Class
public class Dog extends Animal{ @Override public void speak() { System.out.println("Dog barks"); } }
Cat Class
public class Cat extends Animal{ @Override public void speak() { System.out.println("Cat says Meow"); } }
Polymorphism Class (Main Class)
public class Polymorphism { public static void main(String[] args) { //Creating an Animal object of Animal type Animal animal1 = new Animal(); animal1.speak(); //Creating a Cat object of Animal type Animal animal2 = new Cat(); animal2.speak(); //Creating a Dog object of Animal type Animal animal3 = new Dog(); animal3.speak(); } }
Here is the console output of the above code

2. Method Overloading (Static/ Compile-time Polymorphism)
We can overload a method by changing the method signature without changing the name of the method.
Take a look at the following code snippet to understand the concept simply
Animal class
public class Animal { public void speak(){ System.out.println("Animals speak"); } public void A(){ System.out.println("No parameters - void"); } public void A(int a, int b){ System.out.println("Two int parameters (" + a + ", " + b + ") - void"); } public double A(double a){ System.out.println("One double parameter (" + a + ") - return a value"); return a; } }
Polymorphism class (Main class)
public class Polymorphism { public static void main(String[] args) { //Creating an Animal object of Animal type Animal animal1 = new Animal(); animal1.A(); animal1.A(10, 20); animal1.A(54.3); } }
Here is the console output of the above code

I think I gave you guys a clear simple explanation about Java Polymorphism concept.
Thank you for reading my article. I hope you learned something valuable from it. If you did, drop a like and follow my blog to get notifications when I publish new articles. I write articles about coding, cricket and things that I find interesting. I try to publish articles every other day.
Have a nice day ✌