POLYMORPHISM:

Uzair Ahmed
Nov 4 · 2 min read

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word “poly” means many and “morphs” means forms. So polymorphism means many forms. When applied to object oriented programming languages like Java, it describes a language’s ability to process objects of various types and classes through a single, uniform interface.

Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.

Static Polymorphism:

In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters.

At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile time polymorphism or static binding.

Example:

class DemoOverload{

public int add(int x, int y){ //method 1

return x+y;

}

public int add(int x, int y, int z){ //method 2

return x+y+z;

}

public int add(double x, int y){ //method 3

return (int)x+y;

}

public int add(int x, double y){ //method 4

return x+(int)y;

}

}

class Test{

public static void main(String[] args){

DemoOverload demo=new DemoOverload();

System.out.println(demo.add(2,3)); //method 1 called

System.out.println(demo.add(2,3,4)); //method 2 called

System.out.println(demo.add(2,3.4)); //method 4 called

System.out.println(demo.add(2.5,3)); //method 3 called

}

}

Dynamic Polymorphism:

Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called.

Have a look at the following example.

class Vehicle{

public void move(){

System.out.println(“Vehicles can move!!”);

}

}

class MotorBike extends Vehicle{

public void move(){

System.out.println(“MotorBike can move and accelerate too!!”);

}

}

class Test{

public static void main(String[] args){

Vehicle vh=new MotorBike();

vh.move(); // prints MotorBike can move and accelerate too!!

vh=new Vehicle();

vh.move(); // prints Vehicles can move!!

}

}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade