Question #124060

Design an abstract class GeometricObject with lineColor as data member. GeometricObject must ensure that its children implement calcArea() method. Design Rectangle and Circle classes as children of GeometricObject class with overridden toString() method to return “ Rectangle with ‘w’ width and ‘h’ height is drawn” OR “Circle with ‘r’ radius is drawn”.

- The attribute of Rectangle are length and width

- The attribute of Circle is radius


*Hint:

Area of Circle= πr2

Area of Rectangle=w*l

Expert's answer


File GeometricObject.java:

public abstract class GeometricObject {
    protected String lineColor;

    public GeometricObject() {
        this.lineColor = "black";
    }

    protected GeometricObject(String lineColor) {
        this.lineColor = lineColor;
    }

    // Subclasses should implement this method.
    public abstract float calcArea();
}


File Circle.java:

public class Circle extends GeometricObject {
    private int radius;

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

    public Circle(int radius, String lineColor) {
        super(lineColor);
        this.radius = radius;
    }

    @Override
    public float calcArea() {
        return (float) (Math.PI * radius * radius);
    }

    @Override
    public String toString() {
        return "Circle with ‘" + radius + "’ radius is drawn";
    }
}


File Rectangle.java:

public class Rectangle extends GeometricObject {
    private int length;
    private int width;

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

    public Rectangle(int length, int width, String lineColor) {
        super(lineColor);
        this.length = length;
        this.width = width;
    }

    @Override
    public float calcArea() {
        return width * length;
    }

    @Override
    public String toString() {
        return "Rectangle with ‘" + width + "’ width and ‘" + length + "’ height is drawn";
    }
}
LATEST TUTORIALS
APPROVED BY CLIENTS