所以我正在尝试为我的一个教程编写一些代码。输入和预期输出如下:
> 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 类中,因为代码以其他方式编译。
SMILET
MYYA
相关分类