标签:inheritance abstract-class java
因此,我正在尝试为我的其中一篇教程编写一些代码.输入和预期输出是这样的:
> 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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。