2

私はそれが絶対に退屈な質問であることを知っています(とても初心者です)が、私は立ち往生しています。あるオブジェクトのフィールドに別のオブジェクトからアクセスするにはどうすればよいですか? 質問 => Test02 オブジェクトを 2 回作成しないようにする方法は? (1 回目 => main() ループから、2 回目 => 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;
}
4

3 に答える 3

2

Test01 で test02 をインスタンス化するか (コンストラクターなど)、インスタンス化されたオブジェクトをメインで 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;
    }
}
于 2012-11-04T15:18:29.143 に答える
1

のインスタンスを作成していないため、のコンストラクターからアクセスしようとするたびにTest02が取得されます。NullPointerExceptiontest02Test01

これを解決するには、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;
    }
}

Test02または、 fromのインスタンスを渡すことができますMain-

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

于 2012-11-04T15:14:50.317 に答える
1
Test02 test02 = new Test02();

作成された test02 オブジェクトには、メイン メソッドのみのスコープがあります。

x = test02.x;オブジェクトが作成されていないため、null ポインターが返されます。

于 2012-11-04T15:16:44.570 に答える