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

时间:2012-06-07 13:43:37

标签: java class inheritance

我有超级班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字段设置为类名,而无需手动将其作为字符串传递?

3 个答案:

答案 0 :(得分:8)

你不需要这样做。

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

答案 1 :(得分:1)

你也可以这样做

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

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

答案 2 :(得分: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"