2016-12-15 69 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); 
    } 
}