我可以调用超级构造函数并在java中传递类名吗?

use*_*572 4 java inheritance class

我有超类Vehicle,有它的子类PlaneCar.车辆从具有final string name;场的类延伸,该场只能从构造器设置.

我想将此字段设置为类的名称,因此Car的名称将为Car,Plane将为Plane,Vehicle将为Vehicle.我首先想到的是:

public Vehicle() {
    super(getClass().getSimpleName()); //returns Car, Plane or Vehicle (Subclass' name)
}
Run Code Online (Sandbox Code Playgroud)

但这给了我错误:Cannot refer to an instance method while explicitly invoking a constructor.

如何将name字段设置为类名,而不是手动将其作为String传递?

SLa*_*aks 8

你不需要这样做.

您可以getClass().getSimpleName()直接从基础构造函数调用.