以下代码显示错误Constructor call must be the first statement in a constructor
public class Vehicle {
private String type;
private int age;
private String model;
private float price;
public void vehicle(String type, int age, String model, float price){
this.type = type;
this.age = age;
this.model = model;
this.price = price;
}
}
Car类扩展了Vehicle;
public class Car extends Vehicle {
private int numberOfDoors;
public void car(String type, int age, String model, float price, int numberOfDoors){
super(type, age, model, price); //Error:Constructor call must be the first statement in a constructor
this.numberOfDoors = numberOfDoors;
}
}
这不是第一句话吗?
否。类的构造函数必须命名为"Car"。您有一个方法"car"(小写),所以super
不是构造函数的第一个语句。
这不是第一句话吗?
是的。
但信息显示:
"构造函数调用必须是构造函数中的第一条语句。"
并且CCD_ 3不是CCD_ 4的构造函数。相反,它是一个名为car
的方法,它被声明为不返回任何内容。
经验教训:
-
构造函数的名称必须与类的名称相同。
-
构造函数从来没有声明的返回类型(或
void
)。 -
如果您忽略Java的标识符样式规则,您很可能会自食其果。类名应始终以大写字母开头。