When you say "you're stuck", do you mean you're getting NullPointerException
s?
The variables PointerToB
and PointerToC
are static and will indeed be set by ClassA
's constructor. However, this will only be run when an instance of ClassA is created.
What you were probably thinking of instead is a static initialiser block, which will be run when the class is loaded:
public class ClassA {
public static ClassB PointerToB;
public static ClassC PointerToC;
static {
PointerToB = new ClassB();
PointerToC = new ClassC();
}
public ClassA() {
PointerToB.doSthB();
}
}
Now whenever you access these variables they will be non-null. In this particular case, since you're not doing anything complicated, you may as well initialise them in the declaration:
public class ClassA {
public static ClassB PointerToB = new ClassB();
public static ClassC PointerToC = new ClassC();
}
This is functionally identical, but is arguably easier to write and understand.
Edit: As an aside, note that your code is actually quite nasty as it is now - there's a hidden temporal dependence, in that it would appear to work correctly so long as some bit of code constructed an instance of ClassA before you accessed the static variables. This could have worked quite happily (by coincidence) for months, before someone makes some tiny change (e.g. create a ClassA on demand rather than eagerly) and BANG, all of a sudden some completely unrelated code starts breaking.
Even worse than this temporal dependency, you're opening yourself up to race conditions that you probably hadn't even considered. Both of my versions above will guarantee that the static variables are initialised before you can do anything in the class, but this isn't the case with your version. You're setting them on each and every time that the class is constructed. If one thread's calling the constructor while another thread is accessing the variable, the results are undefined and could manifest as "random" crashes, weird data issues or other things.
Even if you avoid this, the actual object references will change over time, so you might call something like PointerToC.doSthC()
(let's say it increments a counter in C) - this will correctly make the counter 1, but at a later point in the program, PointerToC
has been reset to a new instance of ClassC
and the counter is back at zero again!
I don't mean to show you up or anything by this, merely to point out how it's important to think about data consistency issues - and how just because something compiles, and in fact even if it works (right now) it's not necessarily correct.