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;
}
4

3 回答 3

2

您必须在 Test01 中实例化 test02 (例如在构造函数中)或将 main 中的实例化对象传递给 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,因此NullPointerException每当您尝试test02Test01的构造函数访问时都会得到 a 。

为了解决这个问题,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;
    }
}

或者,您可以传递Test02from的实例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 对象仅适用于 main 方法。

x = test02.x;它会给出空指针,因为没有创建对象!

于 2012-11-04T15:16:44.570 回答