Java 访问对象变量时出错
以下代码给出了一个错误:Java 访问对象变量时出错,java,Java,以下代码给出了一个错误: 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); }
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);
}
}
错误是
无法解析年龄或年龄不是字段
我如何才能访问
Test.age
?您没有将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);
}
}
公共类测试{
int age;//在Test
中没有字段age
。在Test
的构造函数中有一个名为age
的参数,但没有字段。可以使用如下行声明年龄:
private int age;
插入到构造函数的第一行上方,这将是实例变量的正常位置
缺少class字段,age对于方法是本地的,并且对于同一个类或类外的任何其他方法都无法访问。它的存在只是为了测试构造函数
这是因为age
是Test
constructor的一个局部变量,将其设置为一个字段您应该检查Java的基础知识,您可以检查关于变量、范围的主题
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);
}
}