Polymorphism in java

Polymorphism in the real world

Polymorphism means more than one form. Water can be of any form solid, liquid, or gas.

Polymorphism in Programming

In Java polymorphism is a mechanism in which something behaves differently based on its call. Let us take the example of the + operator and see the below example.

PolymorphismTest.java

package com.w3schools;

public class PolymorphismTest {
    public static void main(String args[]){
        //+ operator to add two numeric values
        System.out.println(50 + 30);
        //+ operator to concatenate two strings.
        System.out.println("Hello " + "Folks!");
    }
}

Output:

80
Hello Folks!

In the above example + operator behaves differently based on the type of argument. When arguments are of integer type it acts as an additional operator and when arguments are of String type it acts as a concatenation operator.

Polymorphic object

In Java an object that can pass two or more IS-A tests. All objects in Java are polymorphic in nature because they passed the IS-A test at least for their own type and Object class type.

Types of polymorphism

  1. Method overloading: Static/compile time polymorphism.
  2. Method overriding: Dynamic/run time polymorphism.

 

Please follow and like us:
Content Protection by DMCA.com