Java,在超类型构造函数之前无法引用

时间:2015-10-13 15:40:59

标签: java

由于一个错误(将name而不是newName传递给第二个构造函数),我遇到了这种情况,但很奇怪为什么下面的代码没有编译和抱怨"不能超类型构造函数之前的引用"。谢谢

public class Plant {
    String name;

    public Plant(){

        System.out.println("Constructor running");
    }

    public Plant(String newname ) {

        this(name, 7); //compiler error, cannot reference Plant.name before supertype constructor has been called

        System.out.println("Constructor 2 running");
    }

    public Plant(String maximax, int code){
        this.name = maximax;
        System.out.print("Constructor 3 running");
    }

    private void useName(String name){
        ;
    }
}

1 个答案:

答案 0 :(得分:0)

*实际上你试图在这里显式调用构造函数,引用类的实例字段,这是不允许的。如果您想要使用此上下文访问实例字段,则必须使该字段成为类的静态成员,如 - >

public class Plant {

          static String name;  // make instance field static
    public Plant(){
      System.out.println("Constructor running");
    }
    public Plant(String newname ) {
      this(name, 7); // now your code will work here
      System.out.println("Constructor 2 running");
    }
    public Plant(String maximax, int code){
      this.name = maximax;
      System.out.print("Constructor 3 running");
    }
   private void useName(String name){
       ;
   }
}