2015-10-13 761 views
0

由于存在一个错误(将name而不是newName传递给第二个构造函数),但我很好奇为什么下面的代码没有编译并且抱怨“在超类型构造函数之前无法引用”。由于Java在超类型构造函数之前无法引用

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){ 
     ; 
    } 
} 

回答

0

*其实你[R试图在这里明确地调用构造函数参照这是不符合的这种情况下允许类的实例字段。如果你想访问实例字段的上下文,你必须使该字段的静态成员类似于 - >

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){ 
     ; 
    } 
} 
相关问题