继承 super() 构造函数中的第一条语句

inheritance super() first statement in a constructor

下面的代码显示错误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;
    }
}

并且汽车 class 扩展车辆;

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;
    }
}

不是已经表白了吗

没有。 class 的构造函数必须命名为 "Car"。您有一个方法 "car"(小写),因此 super 不是构造函数的第一条语句。

Isn't it already first statement?

是的。

但是消息说:

"Constructor call must be the first statement in a constructor."

... 并且 public void car(...) 不是 Car 的构造函数。相反,它是一个名为 car 的方法,它已被声明为 return 什么都没有。

课程:

  1. 构造函数的名称必须与 class 的名称相同。

  2. 构造函数从来没有声明的 return 类型(或 void)。

  3. 如果你忽视Java的标识符样式规则,你很可能搬起石头砸自己的脚。 class 名称应始终以大写字母开头。