There are a couple of classes ClassA and ClassB. ClassB is used in ClassA. The third class Manager is responsible for creating instances of the class, but we need static ClassA and static ClassB in Manager.
When written this way, a NullPointerException is thrown because classA.classB == null – I can’t figure out why. I redid the Manager class so that everything works correctly, but I would like to understand why this particular option does not work.
I expected that it would work like this: when the Manager class is first accessed, its fields will be initialized, after which the get methods will return not null ClassA and ClassB objects.
class Main {
public static void main(String[] args) {
ClassA classA = Manager.getDefaultA();
System.out.println(classA.classB);
}
}
public class ClassA {
ClassB classB = Manager.getDefaultB();
}
public class ClassB {
}
public class Manager {
static ClassA classA = new ClassA();
static ClassB classB = new ClassB();
public static ClassA getDefaultA() {
return classA;
}
public static ClassB getDefaultB() {
return classB;
}
}
>Solution :
A NullPointerException
is being thrown because of the order in which the fields of Manager
class are initialized.
In your current implementation, when the JVM loads the Manager class, it will first initialize the classA
and classB
fields before calling the getDefaultA()
and getDefaultB()
methods. Since classA
and classB
are initialized before calling the getDefaultB()
method, the classB
field inside the classA
instance is still null
, which causes the NullPointerException
when you try to access it.
To fix this issue, try initializing classB
before classA
in the Manager class. This way, when classA
is initialized, the classB
field inside it will already have a non-null value:
Note: I removed the public
‘s since they were not required to illustrate the actual underlying issue.
class Main {
public static void main(String[] args) {
ClassA classA = Manager.getDefaultA();
System.out.println(classA.classB);
}
}
class ClassA {
ClassB classB = Manager.getDefaultB();
}
class ClassB {
}
class Manager {
static ClassB classB = new ClassB();
static ClassA classA = new ClassA();
public static ClassA getDefaultA() {
return classA;
}
public static ClassB getDefaultB() {
return classB;
}
}
Output:
ClassB@548c4f57