Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a Square class that inherits from Rectangle class

So I am trying to write some code for one of my tutorials. The input and expected output is as such:

> Square s = new Square(5);
> s.toString();
< Square with area 25.00 and perimeter 20.00

The following is my code:

abstract class Shape {
    protected String shapeName;

    public abstract double getArea();
    public abstract double getPerimeter();

    @Override
    public String toString() {
        return shapeName + " with area " + String.format("%.2f", getArea()) +
            " and perimeter " + String.format("%.2f", getPerimeter());
    }
}

class Rectangle extends Shape {
    protected double width;
    protected double height;

    public Rectangle(double width) {
        this.shapeName = "Rectangle";
        this.width = this.height = width;
    }

    public Rectangle(double width, double height) {
        this.shapeName = "Rectangle";
        this.width = width;
        this.height = height;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }
}

class Square extends Rectangle {

    public Square(double side) {
        this.shapeName = "Square";
        this.width = this.height = side;
    }
}

The problem is when I try to compile it, this error occurs:

error: no suitable constructor found for Rectangle(no arguments)
    public Square(double side) {
                               ^
    constructor Rectangle.Rectangle(double) is not applicable
      (actual and formal argument lists differ in length)
    constructor Rectangle.Rectangle(double,double) is not applicable
      (actual and formal argument lists differ in length)

I am unsure about how inheritance works in this case. How could I modify my code such that the input returns the correct output? I presume the error lies solely in the Square class as the code compiles otherwise.

Thanks in advance.

like image 386
ktktktkt Avatar asked Nov 20 '25 20:11

ktktktkt


1 Answers

Design-wise I feel the constructor Rectance( double width ) is un-natural for a rectangle and would remove it. The constructor for the Square should look like this:

 public Square(double side) {
        super(side,side);   // width == height
        this.shapeName = "Square";
 }

To clarify inheritance even more, you could also replace the line this.shapeName= "Rectangle"; with this.shapeName= getClass().getSimpleName(); and remove this.shapeName = "Square"; from Square's constructor.

like image 148
runec Avatar answered Nov 22 '25 16:11

runec