Can anyone tell me how to return an instance of a class in java ???
Yes, just do this:
return instancia;
I'll try to explain it better,
I have a class Server, I instantiate the class thus turning an object I WANT TO RETURN THIS INSTANCE to another method main
, WITHOUT INSTANCING ANOTHER object of that class. Got better understood?
No, it did not get better understood. It's very confusing.
The most obvious suggestion would be to use the singleton. But ...
For your caller, in case it would be a main method and I would assign this to a reference of that class, I just wanted the same instance.
Without being singleton.
Ok, let's look at what we have:
- There is some method that should return to
main
an instance of class Server
. This also means that this method was invoked by main
itself.
- This method should always return the same instance.
- Class
Server
is not a singleton.
So, does something like this solve it?
private static final Server instancia = new Server();
public static void main(String[] args) {
Server instancia = obterInstancia();
}
private static Server obterInstancia() {
return instancia;
}
Or maybe you want to instantiate the class Server
lazy :
private static Server instancia = null;
public static void main(String[] args) {
Server instancia = obterInstancia();
}
private static synchronized Server obterInstancia() {
if (instancia == null) instancia = new Server();
return instancia;
}