我知道这绝对是个无聊的问题(所以新手),但我被困住了。如何从另一个对象访问一个对象的字段?问题 => 如何避免两次创建 Test02 对象?(第一次 => 来自 main() 循环,第二次 => 来自 Test01 的构造函数)?
class Main
{
public static void main(String[] args)
{
Test02 test02 = new Test02();
Test01 test01 = new Test01(); //NullPointerException => can't access test02.x from test01
System.out.println(test01.x);
}
}
class Test01
{
int x;
Test02 test02; //can't access this, why? I creat test02 object in main() loop before test01
public Test01()
{
x = test02.x;
}
}
class Test02
{
int x = 10;
}