4

我有超类Vehicle,它的子类PlaneCar. 车辆从具有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字段设置为类名,而无需手动将其作为字符串传递?

4

3 回答 3

8

你不需要这样做。

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

于 2012-06-07T13:44:44.500 回答
1

你也可以这样做

   //Vehicle constructor
    public Vehicle() {
        super(Vehicle.class.getSimpleName()); 
    }

    //Plane constructor
    public Plane(){
        super(Plane.class.getSimpleName());
    }
于 2012-06-07T13:49:54.330 回答
0

正如编译器告诉您的那样,您不能在调用“super()”方法时调用实例方法。

但是,您可以调用静态方法。此外,在超级构造函数代码本身中,您始终可以调用“getClass()”,它将返回实际的实例类型。

public class A {
  public A() {
      System.out.println("class: " + getClass().getName());
  }
}

public class B extends A {
  public B() {
      super();
  }
}

new A(); --> "class: A"
new B(); --> "class: B"
于 2012-06-07T14:25:02.823 回答