Polymorphism in java with example

In this tutorial, we will see about Polymorphism in java.

Polymorphism in java is one of core Object oriented programming concepts with Abstraction, encapsulation, and inheritance.

Polymorphism means one name many forms. In Java, polymorphism can be achieved by method overloading and method overriding.

There are two types of polymorphism in java.

  • Compile time polymorphism.
  • Run time polymorphism.

Compile time Polymorphism

Compile time Polymorphism is nothing but method overloading in java. You can define various methods with same name but different method arguments. You can read more about method overloading.

Let’s understand with the help of example:

When you run above program, you will get below output:

Integer: 20
Double 30.0
Integer a and b:20 30

As you can see here, we have used same method name but different method arguments.The compiler will call appropriate method based on best-matched arguments.

Runtime Polymorphism

Runtime Polymorphism is nothing but method overriding in java.If subclass is having same method as base class then it is known as method overriding Or in another word, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding.

Let’s say you have parent class as Shape and child class as Rectangle and circle.

When you run above program, you will get below output:

Drawing Rectangle
Drawing Circle

Please note that we are assigning child object to parent object here.

As you can see we have overridden draw methods in child class Rectangle and Circle.JVM decides at runtime which method it needs to call depending on the object assignment. That’s why this is known as Run time polymorphism.

That’s all about Polymorphism in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *