iI have some trouble getting sth like this to work in java:
public class ClassA {
public static ClassB PointerToB;
public static ClassC PointerToC;
public ClassA() {
PointerToB = new ClassB();
PointerToC = new ClassC();
PointerToB.doSthB();
}
}
public class ClassB {
public void doSthB() {
ClassA.PointerToC.doSthC();
}
}
public class ClassC {
public void doSthC() {
// ...
}
}
say i have these classes where my “main” class (“A”) has several members. these pointers to other objects (“B”, “C”) are made static so code in “B” can access (non-static) methods in “C”.
i know that static methods can only access other static methods and/or variables, but since the REFERENCE to these classes is static – and not the actual class itself – it should work fine this way – shouldn’t it?
i’m a bit stuck here, since this kind of access crashes my application all the time 🙁
i need ClassB to access (non-static) methods in ClassC without passing all the references to A or C along. how do i do this?
Well, other than your constructor for
ClassAbeing malformed (you’re missing the brackets), that code compiles… but until you construct an instance ofClassA, bothPointerToBandPointerToCwill be null. If you want to just initialize them once, do so in static initializers – e.g. with the declarations:Even so, there are two nasty bits of design here (IMO):