Post

Created by @nathanedwards
 at November 1st 2023, 6:21:09 pm.

Question:

Consider the following inheritance hierarchy:

class Shape {
    protected double area;

    public double getArea() {
        return area;
    }

    public void calculateArea() {
        // To be implemented in the subclasses
    }
}
class Rectangle extends Shape {
    private double length;
    private double width;

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

    @Override
    public void calculateArea() {
        area = length * width;
    }
}
class Circle extends Shape {
    private double radius;

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

    @Override
    public void calculateArea() {
        area = Math.PI * Math.pow(radius, 2);
    }
}

You are tasked with creating objects of the Shape class and its subclasses and calling their calculateArea methods. Write a program that does the following:

  1. Create an object of the Rectangle class with a length of 5.5 units and width of 4.2 units.
  2. Create an object of the Circle class with a radius of 3.8 units.
  3. Call the calculateArea method for each object.
  4. Print the calculated area for each object.

Write the complete program to accomplish the above tasks.

Answer:

public class ShapeDemo {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle(5.5, 4.2);
        Circle circle = new Circle(3.8);

        rectangle.calculateArea();
        circle.calculateArea();

        System.out.println("Area of rectangle: " + rectangle.getArea());
        System.out.println("Area of circle: " + circle.getArea());
    }
}

Explanation:

  1. In the main method, we create an object rectangle of the Rectangle class with a length of 5.5 units and width of 4.2 units.
  2. We create another object circle of the Circle class with a radius of 3.8 units.
  3. We then call the calculateArea method for each object, which calculates and stores the area of the shape in the area variable of the respective object.
  4. Finally, we print the calculated area for each object using the getArea method inherited from the Shape class, resulting in the area of the rectangle and circle being displayed on the console.