【发布时间】:2012-06-11 13:59:57
【问题描述】:
我有超类Vehicle,还有它的子类Plane 和Car。车辆从具有final string name; 字段的类扩展而来,该字段只能从构造函数中设置。
我想将此字段设置为类的名称,因此 Car 的名称为 Car,Plane 的名称为 Plane,Vehicle 的名称为 Vehicle。我想到的第一件事:
public Vehicle() {
super(getClass().getSimpleName()); //returns Car, Plane or Vehicle (Subclass' name)
}
但这给了我错误:Cannot refer to an instance method while explicitly invoking a constructor。
如何仍然将name 字段设置为类名,而无需手动将其作为字符串传入?
【问题讨论】:
-
为什么?该类可以随时获取自己的名称,无需将其存储在字段中。
标签: java class inheritance