我知道这是绝对沉闷的问题(所以新手),但我卡住了。如何从另一个对象访问一个对象的字段? 问题=>如何避免两次创建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;
}
你明白了!第二种方式=正是我需要的!我很开心! – Alf