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;
}
Either you have to instantiate test02 in Test01 (eg. in constructor) or pass the instantiated object in main to Test01
so either:
or