2012-11-04 172 views
2

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

回答

2

要麼你必須實例test02在TEST01或主要通過實例化對象TEST01

所以要麼(例如,在構造函數):

public Test01() 
    { 
     x = new Test02(); 
//... 
    } 

class Test01 
{ 
    int x; 
    Test02 test02; //the default value for objects is null you have to instantiate with new operator or pass it as a reference variable 

    public Test01(Test02 test02) 
    { 
     this.test02 = test02; // this case test02 shadows the field variable test02 that is why 'this' is used 
     x = test02.x; 
    } 
} 
+0

你明白了!第二種方式=正是我需要的!我很開心! – Alf

1

你沒有創建的Test02一個實例,所以你會得到一個NullPointerException每當你嘗試從Test01的構造函數訪問test02

爲了解決這個問題,重新定義你Test01類的構造函數這樣的 -

class Test01 
{ 
    int x; 
    Test02 test02; // need to assign an instance to this reference. 

    public Test01() 
    { 
     test02 = new Test02(); // create instance. 
     x = test02.x; 
    } 
} 

或者,你可以從Main合格Test02一個實例 -

class Main 
{ 
    public static void main(String[] args) 
    { 
     Test02 test02 = new Test02(); 
     Test01 test01 = new Test01(test02); //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(Test02 test02) 
    { 
     this.test02 = test02; 
     x = test02.x; 
    } 
} 

class Test02 
{ 
    int x = 10; 
} 

的原因是,每當你嘗試創建一個Test01的實例,它會嘗試訪問其構造函數中的test02變量。但test02變量此時不指向任何有效的對象。這就是爲什麼你會得到NullPointerException

+0

我知道。我只是不想創建同一個對象兩次? (解決方案abote =>將它作爲參考傳遞給ctor())。它必須工作! – Alf

+0

@Alf:檢查我的編輯。 –

+0

是啊! +1(它的工作) – Alf

1
Test02 test02 = new Test02(); 

test02創建的對象僅適用於主方法。

x = test02.x;它會給出空指針,因爲沒有創建對象!