I think the answer you are looking for is a "singleton pattern." Here you create only one instance of the class for use in other places. Here is a good read link . Here's a wikipedia page on it with some Java examples.
So your code will look something like this:
public class A { private final static A instance = new A(); 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 cannot also have an instance of B and call methods B in its own methods. What you cannot do with this cross-dependency is to call any other method in the constructor.
In general, by the way, these patterns should be used sparingly. The best way to achieve this is to inject dependencies instead of global references. Cross-injection is possible, but again, it should be used sparingly. A better solution would be to refactor classes with linear dependencies.
Are there any concepts in Java that would refer to an actual object (like a pointer) to an object as a variable instead of creating a copy of the object?
Java is passed by value, but the value of any object is a reference to the object (similar to pointers to C, although they are not a memory address). Therefore, if you have an instance of A and assign it to another field, this field will be the same value and will refer to the same instance of A
source share