2012-11-04 171 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;它会给出空指针,因为没有创建对象!