Can anyone tell me how to return an instance of a java class???
Yeah, just do that:
return instancia;
I’ll try to explain it better,
I have a Server class, I urge the class to become an object I WANT TO RETURN THIS INSTANCE TO another method main
, WITHOUT INSTANTIATING ANOTHER object of that class. It was better understood?
No, it’s not better understood. It’s super confusing.
The most obvious suggestion would be to use Singleton. But...
For your caller, in this case it would be a main method and I was going to assign it to a reference of that class, I just wanted the instance same.
Other than Singleton.
Okay, let’s look at what we have:
- Is there any method that should return to
main
an instance of the class Server
. This also means that this method was invoked by main
.
- This method should always return the same instance.
- The class
Server
is not an English.
So does something like this solve?
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
lazily (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;
}
Return where to? Which class?
– Maniero
For your caller, in this case it would be a main method and I was going to assign it to a reference of that class, I just wanted the instance same.
– Leonardo ferreira villela mart
<troll> Use
return
. </troll> Singleton, that would be it?– Renan Gomes
You need to give more information than you are doing to have a more accurate answer. I might even try to answer just with this but I probably won’t help you:
– Maniero
Other than Singleton.
– Leonardo ferreira villela mart