I have a java application that creates two static objects in a base class, these objects needs to references throughout classes in the program.
public class Baseclass{
public static ClassA A = new ClassA();
public static ClassB B = new Classb();
...
...
...
}
These objects are referenced in the other classes as a local private variables.
public class ClassA{
private ClassB b = Baseclass.B;
However, both object require each other to function and if I creates a new instance of one of the objects before the other is created, the local variable in the “upper” classes is set to null. Is there any concepts in Java that would reference the actual object (like a pointer) to the object as a variable instead of making a copy of the object?
I think the answer you are looking for is a “singleton pattern”. This is where you create just one instance of a class for use in other places. Here’s a good link to read. Here’s the wikipedia page on it with some java examples.
So your code would look something like this:
Then wherever you want to get an instance of A you would do something like:
There is no reason why
Acould not also have an instance ofBand callB‘s methods in its own methods. What you cannot do with this cross dependency is call any of the other’s methods in the constructor.In general, by the way, these patterns should be used sparingly. A better way to accomplish this is through dependency injection instead of global references. Cross injection is possible but again, it should be used sparingly. A better solution would be to refactor the classes to have linear dependencies.
Java is pass by value but the value of any Object is the reference to the object (similar to pointers in C although they are not a memory address). So if you have an instance of
Aand assign it to another field, that field will be the same value and will be referencing the same instance ofA.