Different object references for the same object (?)

I recently asked how to get a unique instance of a class from another class.

( How to get a specific instance of a class from another class in Java? )

So I'm trying to get it working:

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 the method mainreturns different references to objects.

Application@1430b5c
Application@c2a132

What is wrong with my code?

+5
source share
4 answers

Here's what happens:

  • the program first calls Application application1 = getSharedApplication();
  • which, in turn, calls the static method that calls new Application()- this call requires loading the View class, which is a member Application.
  • View, getSharedApplication(); ( , _application - ). new Application()

2 .

, View v = new View(); , ( View). , , ...

+7

: ! , Application, , .

, :

Application.<init>() line: 21   
Application.getSharedApplication() line: 31 
View.<clinit>() line: 59    
Application.<init>() line: 23   
Application.getSharedApplication() line: 31 

, , ( , ).

+4

,

public static Application getSharedApplication() {

    if(_application == null)
    {
        _application = new Application();
        view = new View();
    }

, . , View , . , , .

, :) :)

+1

getSharedApplication() synchronized. if if .

, , . / , , .

0

All Articles