it might be stupid question, but I dont know the answer to it and I dont know where to search the answer, so it would be nice if someone could help me.
I've a class (lets name it A) with different members and methods. I use the methods of this class in another class (lets name it B).
For every B-Object created I want to use the SAME instance of A. Is that possible? Actually I have a constructor in B where I call A a = new A(); Of course I always get different instances of this class.
How can I now change this? I know it could be possible to solve it with spring framework (inject always the same object into the instances of B), but I cant use it. How else could this problem be solved?
Thank you very much for your help! :-)
Yes, that is of course possible. And it is easy to think about something where it is required. You might have a container which contains childs where the childs need a reference to the parent.
The only way to pass the same object to two functions of different classes is if one class inherits from the other, and the Object is an instance of the inherited class. The other way would be to weakly type the object upon variable definition and function definition.
Having two or more methods named the same in the same class is called overloading. It's not overloading if you have the same method name in two different classes.
Do you really need both classes to depend on each other? A stack overflow has nothing to do with classes referencing each other. It is perfectly possible and supported by Java to do that. The Exception is caused by a too deep recursin, this can happen with one method/class as well.
Yes its possible. You need to define a singleton instance of classA that is static, and use it wherever you want.
So there are multiple ways of doing this:
public class ClassA {
public static ClassA classAInstance = new ClassA();
}
then anywhere you can do
ClassA.classAInstance.whatever();
This is simple, but it might be enough for you.
If you really want to use the singleton pattern, look here for a Java example. The advantage of this approach is that it makes sure that you only have 1 classA instance.
To elaborate on other answers:
public class A
{
private static A instance;
private A()
{
...
}
public static A getInstance()
{
if (instance == null)
instance = new A();
return instance;
}
...
public void doSomething()
{
...
}
}
And then call in B like this:
A.getInstance().doSomething();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With