Sitemap

Java Polymorphism

2 min readAug 23, 2023

--

Polymorphism is a fundamental concept in object-oriented programming where objects of different classes can be treated as objects of a common superclass. This allows different classes to provide a specific implementation of methods defined in a shared interface or superclass, resulting in more flexible and adaptable code.

Get Miraç Balkaya’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s take an example using the concept of geometric shapes. Consider a base class named Shape, and two subclasses named Circle and Rectangle, each representing a specific shape. Each subclass overrides the calculateArea() method to calculate the area of its corresponding shape.

For example:

class Shape {
double calculateArea() {
return 0;
}
}

class Circle extends Shape {
double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape {
double width, height;

Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

@Override
double calculateArea() {
return width * height;
}
}

public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);

System.out.println("Area of shape1: " + shape1.calculateArea()); // Output: Area of shape1: 78.53981633974483
System.out.println("Area of shape2: " + shape2.calculateArea()); // Output: Area of shape2: 24.0
}
}

In this example, the Shape class serves as a common superclass for both Circle and Rectangle subclasses. Each subclass overrides the calculateArea() method to provide its own specific implementation. In the Main class, we create instances of Circle and Rectangle but store them in variables of the Shape type. When we call the calculateArea() method on these instances, Java's polymorphic behavior ensures that the appropriate method from the corresponding subclass is invoked based on the actual object type. This flexibility enables us to treat different objects as instances of a common superclass, promoting code reusability and maintainability.

In essence, polymorphism allows us to abstractly work with various subclasses through a shared interface, enhancing the extensibility and adaptability of our programs.

I hope this article has guided you about polymorphism in Java. Good coding!

--

--