我有以下两门类(class),
abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
//super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
如果我不添加注释行 (//super(drawAPI)) ,我会在 Circle 类的构造函数中收到错误。错误是类形状中的构造函数形状无法应用于给定类型。实际论证和形式论证长度不同
我想知道为什么添加注释行可以解决问题以及它有什么作用?
最佳答案
I want to know why adding commented line fix the problem and what does it do ?
如果构造函数有父类,则构造函数的第一条语句必须调用其父类的构造函数(适用于除 Object
之外的所有类)。
Shape
是Circle
的父级。因此,必须首先在 Circle
构造函数中调用 Shape
构造函数。
问题是 Shape
构造函数没有像您定义带参数的构造函数那样的无参数构造函数。
因此,您必须显式调用此构造函数。
请注意,如果未显式调用父构造函数,编译器会将 super()
调用添加为构造函数主体的第一条语句。
因此,由于父构造函数没有参数,因此不需要在类源代码中调用super()
。编译器将在编译后的类中为您完成此操作。
但在您的实际情况中,编译器无法添加 super()
因为父类没有无参数构造函数。
它将产生无效的构造函数调用:
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(); // Shape with no arg constructor doesn't exist
this.x = x;
this.y = y;
this.radius = radius;
}
因此编译器希望您指定实际定义的父类构造函数的调用:
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
关于java - 实际参数和形式参数长度不同 - 构造函数中存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49966734/