What is polymorphism in java object oriented programming

The ability to exist in different forms is called polymorphism or any java object that can pass more than one IS-A test can be considered as polymorphism .


polymorphism in javaA reference variable can be of only one type , and once declared , that type can never be changed.
polymorphism in javaA reference is a variable , so it can be reassigned to other objects.
polymorphism in javaA reference variable’s type determines the methods that can be invoked on the object the variable is referencing.
polymorphism in javaA reference variable can refer to  object of the same type or can be any subtype.
polymorphism in javaA reference variable can be declared as a class type or an interface type. If the variable is declared as an interface (or abstract)  type, it can reference any object of any class that implements the interface(or abstract class).


polymorphism in javaExample for polymorphism :

Execution Result:

From the above example :
polymorphism in java  solarSystem , Planet , Moon are three classes. solarSystem is the base class, remaining two are derived classes.
polymorphism in java  In the Moon class we created three reference variables(firstObj , secondObj, thirdObj) for solarSystem class with different instantiation.
polymorphism in java  The java compiler looks only the reference type , but not the instance type.
polymorphism in java  In line number 23 , the super class reference refers to the sub class object.In this case the super class reference will invoke the sub class measurements() method at run time (from line number 30).
polymorphism in java  If any method belongs to only sub class (but it is not there in super class) ,so that the super class reference cannot invoke the sub class method like motherPlanet().
polymorphism in java  See line number 32 ,at compile time the compiler used measurements() in solarSystem to validate the statement.At run time, however the JVM invokes measurements() from the Moon class.

Related Posts :
   [will not be published]

^ <