Polymorphism is a Greek word which means "several forms". It is the most important feature of any object-oriented programming language.
Java supports two types of polymorphism-
Reference variable of a superclass can refer to an object of a subclass. When inheritance is performed, the instance variables are bounded at compile time, and methods are bounded at runtime.
class Shape { public void display() { System.out.println("I am a shape"); } } class Square extends Shape { public void display() { System.out.println("I am a square"); } public static void main(String args[]) { Shape s = new Shape(); s.display(); s = new Square(); s.display(); } }
Output
I am a shape I am a square
In the above example, initially the type of reference variable "s" and the type of object referenced by it are the same(Shape), so there is no confusion in the method call.
Later we assign reference variable "s" to an object of Square class. Even though we are calling display() method but JRE is aware that method is called on a Square object so overridden method display() in the Square class is called.
class Car { int speedlimit = 90; } class Hyundai extends Car { int speedlimit = 200; public static void main(String args[]) { Car c = new Car(); System.out.println("Speedlimit = "+c.speedlimit); c = new Hyundai(); System.out.println("Speedlimit = "+c.speedlimit); } }
Output
Speedlimit = 90 Speedlimit = 90
Since, variables are bounded at compile time, so the type of object that the reference variable "c" is pointing does not make any difference. And in both the cases, it will print speedlimit = 90