【问题标题】:Can I call the Super Constructor and pass the Class name in java?我可以调用超级构造函数并在 java 中传递类名吗?
【发布时间】:2012-06-11 13:59:57
【问题描述】:

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

【问题讨论】:

  • 为什么?该类可以随时获取自己的名称,无需将其存储在字段中。

标签: java class inheritance


【解决方案1】:

你不需要这样做。

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

【讨论】:

  • 这个问题是我无法修改基类,因为这是 API(Libgdx 库)的一部分。名称 String 必须通过构造函数传递,并且没有更多的写访问权限。
  • 好吧,我想这最好地回答了我的问题,即使很难,它也不适用于我的情况。我现在只是手动传递名称字符串。
【解决方案2】:

你也可以这样做

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

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

【讨论】:

  • 这将始终返回“Vehicle”,而不是可能的子类的名称。
  • 把子类名放在每个子类的构造函数中。我编辑了答案。
  • 但这就是我不想要的:必须手动定义每个名称。我非常喜欢 getSimpleName,因为它获取实际的子类名称,所以我可以在超类中调用一次,它只获取“实际”对象的类型。
【解决方案3】:

正如编译器告诉你的,你不能在调用“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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多