我想创建我的自定义矩形类,它从Rectangle类扩展 . 我错了那个类Rectangle没有声明构造函数'Rectangle',我看过Rectangle类的源代码,并且有常量构造函数 . 有可能吗?我认为可能的解决方案是使用组合而不是继承 . 谢谢你的回答 .
part of Plot;
class PlotRectangle extends Rectangle{
// Rectangle<int> rectangle; // as variant use composition
String color = "red";
PlotRectangle(int left, int top, int width, int height): super.Rectangle(left, top, width, height){
}
PlotRectangle.withColor(int left, int top, int width, int height, this.color): super.Rectangle(left, top, width, height){
this.color = color;
}
void setColor(String color){
this.color = color;
}
}
2 回答
尝试过并且工作了
正如Günter已经表明的那样,这是非常可能的 .
更具体一点,代码中的错误是对超级构造函数的调用:
super.Rectangle(left, top, width, height)
应为super(left, top, width, height)
.您的语法尝试调用命名构造函数"Rectangle",它等同于
new Rectangle.Rectangle
- 构造函数不存在 . 你想调用"normal"构造函数(new Rectangle
),它只使用super
调用 .