Referencing static object created in one class throughout entire application
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.
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:
public class A {
private final static A instance = new A();
/* private constructor forces you to use the getInstance() method below */
private A() {}
public static A getInstance() {
return instance;
}
}
Then wherever you want to get an instance of A you would do something like:
public class B {
private final A classA = ClassA.getInstance();
...
}
There is no reason why A
could not also have an instance of B
and call B
'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.
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?
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 A
and assign it to another field, that field will be the same value and will be referencing the same instance of A
.
// instantiate a new instance of A
A a1 = new A();
// assign the reference to A to another variable
a2 = a1;
// they are equivalent and both reference the same object
if (a1 == a2) ...