编程语言
首页 > 编程语言> > java-如何设计从Rectangle类继承的Square类

java-如何设计从Rectangle类继承的Square类

作者:互联网

因此,我正在尝试为我的其中一篇教程编写一些代码.输入和预期输出是这样的:

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

以下是我的代码:

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;
    }
}

问题是当我尝试编译它时,会发生此错误:

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)

我不确定在这种情况下继承如何工作.如何修改代码,使输入返回正确的输出?我认为错误仅存在于Square类中,否则代码将编译.

提前致谢.

解决方法:

在设计方面,我认为构造函数Rectance(double width)对于矩形而言是不自然的,因此将其删除.
Square的构造函数应如下所示:

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

为了进一步阐明继承,您还可以替换行this.shapeName =“ Rectangle”;与this.shapeName = getClass().getSimpleName();并删除this.shapeName =“ Square”;来自Square的构造函数.

标签:inheritance,abstract-class,java
来源: https://codeday.me/bug/20191025/1925741.html