Linh
Linh

Reputation: 60923

When static variable be instantiated in Android

For example, I have a class

public class EagerInitializedSingleton {
        private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

        public static EagerInitializedSingleton getInstance(){
            return instance;
        }
}

And my application have 2 activity A.java and B.java (from A I can go to B).
In B activity I have

import EagerInitializedSingleton.java;

public class B{
     onCreate(...){
         EagerInitializedSingleton.getInstance()...
     }
}

My question is when instantiated be instantiated`

If possible, can I check when be instantiated by write Log or something? Any help would be great appreciated.

UPDATE I'm follow here to create EagerInitializedSingleton http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
And they have say

If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method

Like some answer say that instance be instantiated when I call EagerInitializedSingleton.getInstance()..., so who is correct?

Upvotes: 0

Views: 190

Answers (3)

Rohit Arya
Rohit Arya

Reputation: 6791

static variables are initialized when the classloader loads the class for the first time, either through static reference or instance creation. It will be shared across all instances of the class. And remember, it will be initialized before any instance creation of the class.

So, in your question:

When launch application (before Activity start)

No

When import EagerInitializedSingleton.java

No

When EagerInitializedSingleton.getInstance()

Yes

Or whenever you make a static reference to the EagerInitializedSingleton class.

Edit - Just to clear things out as per comments:

Call to getInstance() will not result in instance creation. But the static reference to the class does as the class loads for the first time.

Upvotes: 3

Vucko
Vucko

Reputation: 7479

For starters, this is not a proper singleton implementation. Your constructor, or lack of one, will allow the user to use the default empty constructor and create more objects of that class. Check out how to implement it here or anywhere you find online.

The question you asked has nothing to do with android, it's a plain Java question, having to do with static variables initialization. You can find the answer to that question here.

Upvotes: 1

Cryperian
Cryperian

Reputation: 116

When you call EagerInitializedSingleton.getInstance()

Upvotes: 1

Related Questions