Calculate areas with inheritance and polymorphism

Description: Make an abstract class Shape with an abstract method area(). Write Circle and Rectangle which extend it. Put a circle (radius 2) and a rectangle (3 x 4) in one array and print the total area.

Hint:

  • Use an array of type Shape[].

Solution

abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}

class Rectangle extends Shape {
    private final double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    double area() { return w * h; }
}

public class Main {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(2), new Rectangle(3, 4) };
        double total = 0;
        for (Shape s : shapes) {
            total += s.area();
        }
        System.out.printf("Total area: %.2f%n", total);
    }
}
Output

Total area: 24.57

How it works

  • The loop uses the type Shape. Java calls the area() of the real object (polymorphism).
  • You can add a new shape without changing the loop.

Read Polymorphism and Abstract Classes.


Learn more about the similar topics:
Tutorials
Java Classes and Objects
Java Constructors
Java static and this Keywords
Java Encapsulation and Access Modifiers
Java Inheritance
Java Polymorphism
Java Abstract Classes
Exercises & Assignments
Build a BankAccount class
Calculate areas with inheritance and polymorphism
Use a sealed interface and pattern matching
Interview Questions & Answers
What is a class and an object in Java?
What is a constructor in Java?
What is the difference between a constructor and a method in Java?
What is the this keyword in Java?
What is the static keyword in Java?
What is the final keyword in Java?
What are the four pillars of OOP in Java?