Polymorphism example in java


Hi in this post we will see what is polymorphism in java. I think this is one of favorite interview question as well. Let me start with the definition of polymorphism then we will see example.

polymorphism definition:

property of object to take many different form depending on the type of reference used to access the object.(do not worry it will be clear when we will see example). To be more precise Java object may be accesses using a reference with the same type as the object, a reference that is superclass of the object or a reference of interface that the object implement directly or through a superclass.

Regardless of the type of reference you have for the object in memory, the object itself does not change.

The type of object determines which properties exist within the object in memory.

The type of reference to the object determine which methods and variable are accessible.

Now lets see example. This example is very simple and properly commented. Still if you have any question please do write down your views in comments.

public class Lemur extends Primate implements HasTail{

public int age =10;
public static void main(String[] args) {
Lemur lemur = new Lemur();
lemur.age = 10;
// with lemur reference
System.out.println(lemur.age);
System.out.println(lemur.isTailStriped());

// with HasTail reference
HasTail hasTail = lemur;
/***
* ohhh no hasTail does no anything about age and hasHair of Lemur excuse :(
* System.out.println(hasTail.age);
*/
System.out.println(hasTail.isTailStriped());

// with Primate reference
/***
* ohhh no Primate does no anything about age or TailStriped of Lemur excuse :(
* System.out.println(hasTail.age);
*/
Primate primate = lemur;
System.out.println(primate.hasHair());

}
public boolean isTailStriped() {
return false;
}
}

/**
* *
* abstract is optional for interface
*
*/

abstract interface HasTail{
/***
*
* By default interface methods are public abstract
* By default interface variables are public static final *
* We can interchange change position of public and abstract
*/
public abstract boolean isTailStriped();
}

class Primate{
public boolean hasHair(){
return true;
}
}

Output

10
false
false
true

Hope this example clear your understanding of polymorphism. If you have any doubt or any suggestion please write down to me in comments.