Reputation: 1295
I know it's absolutely dull question (so newbie) but i'm stuck. How can access fields of one object from another object? The question => how to avoid creating Test02 object twice? (1st time => from main() loop, 2nd time => from constructor of 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;
}
Upvotes: 2
Views: 176
Reputation: 29166
You didn't create an instance of Test02
, so you'll get a NullPointerException
whenever you try to access test02
from Test01
's constructor.
To remedy this, redefine your Test01
class's constructor like this -
class Test01
{
int x;
Test02 test02; // need to assign an instance to this reference.
public Test01()
{
test02 = new Test02(); // create instance.
x = test02.x;
}
}
Or, you can pass an instance of 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;
}
The reason is that whenever you try to create an instance of Test01
, it tries to access the test02
variable in its constructor. But the test02
variable doesn't point to any valid object at this moment. That's why you will get NullPointerException
.
Upvotes: 1
Reputation: 2537
Either you have to instantiate test02 in Test01 (eg. in constructor) or pass the instantiated object in main to Test01
so either:
public Test01()
{
x = new Test02();
//...
}
or
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;
}
}
Upvotes: 2
Reputation: 8900
Test02 test02 = new Test02();
test02 object created have scope for main method only .
x = test02.x;
it will give null pointer because no object created !
Upvotes: 1