Java Polymorphism:
An important concept in inheritance is that an object of a class is also an object of any of its superclasses. That concept is the basis for an important OOP feature, called polymorphism, which simplifies the processing of various objects in the same class hierarchy. The word polymorphism, which is derived from the word fragment poly and the word morpho in the Greek language, literally means “multiple forms.” Polymorphism allows us to use the same method call for any object in the hierarchy. We make the method call using an object reference of the superclass. At run time, the JVM determines to which class in the hierarchy the object actually belongs and calls the version of the method implemented for that class.
To use polymorphism. the following conditions must be true:-
- The classes are in the same hierarchy.
- The subclasses override the same method.
- A subclass object reference is assigned to a superclass object reference (i.e., a subclass object is referenced by a superclass reference).
- The superclass object reference is used to call the method.
Types of Polymorphism:
- Static polymorphism or compile time polymorphism or method overloading.
- Dynamic polymorphism or run time polymorphism or method overriding.
Example of Dynamic Polymorphism:


class Shape
{
void draw() {
System.out.println("Drawing......");
}
}
class Circle extends Shape
{
void draw() {
System.out.println("Drawing Circle...");
}
}
class Square extends Shape
{
void draw() {
System.out.println("Drawing Square...");
}
}
class Rectangle extends Shape
{
void draw() {
System.out.println("Drawing Rectangle...");
}
}
public class Method_overriding {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Animal animal = new Animal();
Shape s;
s = new Circle();
s.draw();
s = new Square();
s.draw();
s = new Rectangle();
s.draw();
}
}
Comments (No)