A fundamental concept in Object-Oriented Programming (OOP)! Polymorphism in Java is a powerful feature that allows objects of different classes to be treated as objects of a common superclass. In simpler terms, polymorphism enables you to write code that can work with different data types, without knowing the exact type at compile time.
Let's break it down:
What is Polymorphism?
Poly = Many, Morphism = Forms
So, polymorphism means "many forms". In Java, it allows:
Method overriding (Runtime Polymorphism): A subclass provides a different implementation of a method already defined in its superclass.
Method overloading (Compile-time Polymorphism): Multiple methods with the same name but different parameters (not exactly polymorphism, but often considered a form of it).
Here's an example demonstrating Runtime Polymorphism (Method Overriding):
Example: Shape Classes with Polymorphism
Imagine we have a Shape superclass and three subclasses: Circle, Rectangle, and Triangle. Each shape has an area() method, but the calculation is different for each shape.
java
// Superclass
class Shape {
public void draw() {
System.out.println("Drawing a shape.");
}
// Method to be overridden
public double area() {
System.out.println("Shape area: Not defined");
return 0;
}
}
// Subclass 1
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle.");
}
@Override
public double area() {
return Math.PI * radius * radius; // πr^2
}
}
// Subclass 2
class Rectangle extends Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle.");
}
@Override
public double area() {
return width * height; // w × h
}
}
// Subclass 3
class Triangle extends Shape {
private double base, height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a triangle.");
}
@Override
public double area() {
return 0.5 * base * height; // ½ × b × h
}
}
Now, let's create a polymorphic method that works with any Shape object:
java
public class Main {
// Polymorphic method: accepts any Shape (or its subclasses)
public static void calculateAndDraw(Shape shape) {
shape.draw(); // Calls the overridden draw() method
double area = shape.area(); // Calls the overridden area() method
System.out.println("Area: " + area);
System.out.println(); // Empty line for readability
}
public static void main(String[] args) {
// Create objects of different subclasses
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4, 6);
Shape triangle = new Triangle(3, 7);
// Treat them as Shape objects (Polymorphism in action!)
calculateAndDraw(circle);
calculateAndDraw(rectangle);
calculateAndDraw(triangle);
}
}
Output:
code
Drawing a circle.
Area: 78.53981633974483
Drawing a rectangle.
Area: 24.0
Drawing a triangle.
Area: 10.5
Here's what's happening (the magic of Polymorphism):
calculateAndDraw() method accepts a Shape object as a parameter.
We pass objects of type Circle, Rectangle, and Triangle, which are subclasses of Shape.
Even though the calculateAndDraw() method doesn't know the exact subclass type at compile time, it:
Calls shape.draw() → The correct subclass's draw() method is invoked (e.g., Circle's draw()).
Calls shape.area() → The correct subclass's area() method is invoked, returning the area specific to that shape.
This is Runtime Polymorphism: The JVM determines which method to call based on the actual object type (not the reference type Shape) at runtime.
Key Takeaways:
Polymorphism allows treating objects of different subclasses uniformly as if they were of the same superclass type.
By overriding methods in subclasses, you provide specific implementations for each type.
The correct method to call is resolved at runtime, based on the object's actual class.
Now, imagine extending this example: Adding a Polygon class? No problem! Just create the subclass, override area() and draw(), and the calculateAndDraw() method will work seamlessly with Polygon objects too, without any changes to the existing code.
That's the beauty of polymorphism!
Bonus: If you want to explore Method Overloading (Compile-time Polymorphism), here's a quick example:
java
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) { // Same method name, different params
return a + b;
}
int add(int a, int b, int c) { // Same method name, different params
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(1, 2)); // Calls add(int, int)
System.out.println(calc.add(1.5, 2.5)); // Calls add(double, double)
System.out.println(calc.add(1, 2, 3)); // Calls add(int, int, int)
}
}
Here, the compiler decides which add() method to call based on the number and types of arguments passed.
Hope this explanation made Polymorphism crystal clear! Let me know if you have any questions.