What is polymorphism in java?

Polymorphism in Java
  • Poly means Many and Morphism means Forms. The ability to have more than one form is called Polymorphism. In this language, it allows performing the same action in different ways.
  • There are two types of polymorphism in java, Compile-time Polymorphism (Method Overloading) and (Runtime Polymorphism) Method Overriding.
  • Example: Person can be Teacher at School and Parent at Home at the same time.

Compile-time Polymorphism:

Compile-time polymorphism is also known as static polymorphism where which method to call is resolved at compile time.

We can achieve compile-time polymorphism by

  1. Method overloading
  2. Operator overloading

1. Method Overloading

When in a class having a different method signature (same method name with different arguments) is called method overloading. The method signature is a combination of the name and the method arguments.

Example:

Polymorphism in Java

2. Operator Overloading

In java “+” operator follows different behavior in strings and number formats. If we add 2 numbers it will give the sum of those 2 numbers and if we add 2 strings it will concatenate the strings.

Look at the examples below for operator overloading.

Polymorphism in Java

Runtime Polymorphism:

Runtime polymorphism is achieved by method overriding. When a child class overrides the method in superclass with the same method signature and return type then it’s called a method overriding.

Example: In the below example at runtime JVM checks if the method is present in child class if yes then the child class method is called else parent class method is called.

Polymorphism in Java

Difference between Compile-time and Runtime polymorphism

Polymorphism in Java

Related Posts