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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.