Method Overriding & polymorphism
polymorphism means 'many forms.' It allows a child class to provide a specific implementation of a method defined in the parent class. This enables a single variable to refer to different object types and call the appropriate method. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
45 min•By Priygop Team•Last updated: Feb 2026
polymorphism in Action
Example
class Shape {
String name;
Shape(String name) {
this.name = name;
}
// Method to be overridden
double area() {
return 0;
}
void describe() {
System.out.println(name + " — Area: " + String.format("%.2f", area()));
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
double width, height;
Rectangle(double width, double height) {
super("Rectangle");
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
class Triangle extends Shape {
double base, height;
Triangle(double base, double height) {
super("Triangle");
this.base = base;
this.height = height;
}
@Override
double area() {
return 0.5 * base * height;
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
// polymorphism: parent type holds child objects
Shape[] shapes = {
new Circle(5),
new Rectangle(4, 6),
new Triangle(8, 3),
new Circle(3)
};
System.out.println("=== Shape Areas ===");
double totalArea = 0;
for (Shape shape : shapes) {
shape.describe(); // Calls the correct overridden method!
totalArea += shape.area();
}
System.out.println("Total area: " + String.format("%.2f", totalArea));
}
}Try It Yourself: Employee Payroll
Try It Yourself: Employee PayrollJava
Java Editor
✓ ValidTab = 2 spaces
Java|80 lines|1886 chars|✓ Valid syntax
UTF-8