2015-10-13 58 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){ 
     ; 
    } 
} 
相關問題