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:
Rectangle
class with a length of 5.5 units and width of 4.2 units.Circle
class with a radius of 3.8 units.calculateArea
method 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:
main
method, we create an object rectangle
of the Rectangle
class with a length of 5.5 units and width of 4.2 units.circle
of the Circle
class with a radius of 3.8 units.calculateArea
method for each object, which calculates and stores the area of the shape in the area
variable of the respective object.getArea
method inherited from the Shape
class, resulting in the area of the rectangle and circle being displayed on the console.