我知道这绝对是一个沉闷的问题(所以是新手),但我被困住了。如何从另一个对象访问一个对象的字段?
问题=>如何避免两次创建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;
}

最佳答案

您必须在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;
    }
}

关于java - 从另一个访问一个对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13219787/

10-10 22:47