Polymorphism means one name but many forms. In Java, we can achieve Polymorphism by method overloading and overriding.

Overloading

Overriding

Below example explains how method overloading and overriding works in Java.

package polymorphism;

/**
 * Created by ssalunke on 19/04/2016.
 */
public class Polymorphism {

    public static void main(String [] args){

        //method overloading - Same method name but different arguments
        String city = "Bali";
        System.out.println(city.substring(0));
        System.out.println(city.substring(0, 3));

        //Method overriding
        Polymorphism p = new Polymorphism();

        //toString method is already defined in java.lang.Object class
        //But we have over-ridden that method in class Polymorphism

        System.out.println(p.toString());

    }

    @Override
    public String toString(){
        return "Polymorphism - " + this.hashCode();
    }
}
Here is the output of above code.

Bali
Bal
Polymorphism – 999966131

Web development and Automation testing

solutions delivered!!