2016-12-15 2 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

Там нет поля age в Test. Существует параметр с именем age в конструкторе Test, но нет поля. Вы можете объявить возраст с линией, как:

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); 
    } 
} 
Смежные вопросы