Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've created the following class with the main method, which creates new instance of Application and instances of ApplicationModel, ApplicationView and ApplicationController for this particular Application.

public class Application
{

    // Variables

    private ApplicationSettings         settings;
    private ApplicationModel            model;
    private ApplicationView             view;
    private ApplicationController       controller;

    // Constructor

    public Application()
    {
        settings        = new ApplicationSettings();
        model           = new ApplicationModel();
        view            = new ApplicationView(model);
        controller      = new ApplicationController();
    }

    // Main method

    public static void main(String[] args)
    {
        Application application = new Application();
    }

    // Getters for settings, model, view, controller for instance of Application

}

I know, that there will always be only one unique instance of Application.

And I want to get this particular instance in my ApplicationModel, ApplicationView and ApplicationController classes.

How is it possible?

like image 782
Edward Ruchevits Avatar asked Aug 16 '12 12:08

Edward Ruchevits


People also ask

How do I find the instance of a class in java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

How do I get a singleton instance from another class?

You can do this: var mainSingleton = singleton<main>. instance; and it will always return the same instance of main .

Can a java class contain an instance of another class?

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.


1 Answers

I would use a singleton on Application class.

Put a public static method to return your one and only application instance.

public class Application
{
    private Application() { } // make your constructor private, so the only war
                              // to access "application" is through singleton pattern

    private static Application _app;

    public static Application getSharedApplication() 
    {
        if (_app == null)
            _app = new Application();
        return _app;
    }
}

You can read more about singleton design pattern here.

Every time you need the one and only Application instance, you do:

Application app = Application.getSharedApplication();
like image 69
Pablo Santa Cruz Avatar answered Oct 04 '22 07:10

Pablo Santa Cruz