Polymorphism in Java is the ability of an object to take on multiple forms. This means that an object can be treated as an instance of its parent class or any of its subclasses. In other words, polymorphism allows a single interface to be used for different types of objects.
One of the most common examples of polymorphism in Java is using a parent class reference to hold an instance of a child class. For example, consider the following class hierarchy:
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
public void draw() {
System.out.println("Drawing a square");
}
}
In this example, Shape is the parent class, and Circle and Square are child classes that inherit from Shape. Both Circle and Square have their own implementation of the draw() method.
Now, consider the following code:
Shape s = new Circle();
s.draw(); //Output : Drawing a circle
s = new Square();
s.draw(); //Output : Drawing a square
Here, we create a Shape reference variable s and assign it an instance of Circle. When we call the draw() method on s, it calls the draw() method of the Circle class. Later, we assign s an instance of Square, and now when we call the draw() method on s, it calls the draw() method of the Square class.
This is an example of polymorphism, where the same reference variable s is used to refer to different types of objects (an instance of Circle and an instance of Square) and call their respective draw() method.
Another example of polymorphism is using a parent class array to hold child class objects. For example:
Shape[] shapes = new Shape[2];
shapes[0] = new Circle();
shapes[1] = new Square();
In this example, the shapes array is declared as an array of Shape objects, but we can assign it instances of Circle and Square because they are both subclasses of Shape.
In short, polymorphism in Java allows us to use a single interface to refer to different types of objects, which makes our code more flexible and reusable.