I have asked about getting unique instance of class from another class recently.
( How to get specific instance of class from another class in Java? )
So, I am trying to make it work:
My Application:
public class Application
{
// I will always have only one instance of Application
private static Application _application;
// Every instance of Application (one in my case) should have its own View
private View view;
// Constructor for new instance of Application
private Application()
{
view = new View();
}
// Getter for my unique instance of Application
public static Application getSharedApplication()
{
if (_application == null)
_application = new Application();
return _application;
}
// Main class
public static void main(String[] args)
{
// So I'm accessing my instance of Application
Application application1 = getSharedApplication();
// Here is object reference
System.out.println(application1);
// And now I'm accessing the same instance of Application through instance of View
Application application2 = application1.view.getApplication();
// Here is object reference
System.out.println(application2);
}
}
My View:
public class View
{
// I'm accessing my instance of Application again
public static Application application = Application.getSharedApplication();
// This method should return my unique instance of Application
public Application getApplication()
{
return application;
}
}
The problem is that main method returns different object references.
Application@1430b5c
Application@c2a132
What’s wrong with my code?
Here is what happens:
Application application1 = getSharedApplication();new Application()– that call needs to load the View class, which is a member ofApplication.getSharedApplication();(note that at this stage,_applicationis still null). That creates anew Application()tooYou now have 2 Application instances.
Note that if you add
View v = new View();as the first line of your main, you only have one instance of Application (which gets loaded once from the static variable of View). That makes sense when you think hard about it but is not very intuitive…