我知道這是絕對沉悶的問題(所以新手),但我卡住了。如何從另一個對象訪問一個對象的字段? 問題=>如何避免兩次創建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