2016-12-15 86 views
-2

下面的代碼給出了一個錯誤:錯誤的訪問對象變量

public class Test { 
    public Test(int Age){ 
     int age = Age ; 
    } 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Test gg = new Test(5); 
     System.out.println(gg.age); 
    } 

} 

的錯誤是

age cannot be resolved or is not a field

我怎麼能夠訪問Test.age

+1

,這是因爲'age'是一個局部變量來'Test'構造,使之成爲場 –

+0

您應該檢查的Java的基礎知識,您可以檢查有關變量的話題,範圍 – grsdev7

回答

3

您沒有使age成爲一個字段。只是構造函數的局部變量。我想你想要的東西一樣,

public class Test { 
    int age; // <-- a field. Default access for this example. private or protected 
      //  would be more typical, but package level will work here. 
    public Test(int Age){ 
     this.age = Age; // <-- "this." is optional, but indicates a field. 
    } 
    public static void main(String[] args) { 
     Test gg = new Test(5); 
     System.out.println(gg.age); 
    } 
} 
0

有一個在Test沒有現場ageTest的構造函數中有一個名爲age的參數,但沒有字段。你可以聲明年齡有這樣一行:

private int age; 

構造函數的第一行上方插入,這將是一個實例變量的正常位置。

-1

You are missing the class field, age is local to method and is not accessible to any other method to the same class or outside of the class. It only exist to Test constructor.

public class Test { 
    public int age; 
    public Test(int Age){ 
     age = Age ; 
    } 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     Test gg = new Test(5); 
     System.out.println(gg.age); 
    } 
}