user1050619
user1050619

Reputation: 20916

declaring instance keyword in java

I see a "instance" keyword being declared in my java code declaration of a ENUM.Can someone explain how this keyword works?

Java code:-

public enum TodoDao {
    instance;

    private Map<String, Todo> contentProvider = new HashMap<String, Todo>();

    private TodoDao() {
        Todo todo = new Todo("1", "Learn REST");
        todo.setDescription("Read http://www.vogella.com/articles/REST/article.html");
        contentProvider.put("1", todo);
        todo = new Todo("2", "Do something");
        todo.setDescription("Read complete http://www.vogella.com");
        contentProvider.put("2", todo);
    }
    public Map<String, Todo> getModel(){
        return contentProvider;
    } 
} 

Upvotes: 7

Views: 12570

Answers (3)

GeertPt
GeertPt

Reputation: 17874

It is the best way to implement the GoF singleton pattern, according to Joshua Bloch, see related question: What is an efficient way to implement a singleton pattern in Java?

According to the java style guide, it should be all caps, though, i.e. INSTANCE.

To use this, you can call the following from any part of the code:

Map<String, Todo> todos = TodoDao.INSTANCE.getModel();

And you can be certain that the initialization will happen only once.

Upvotes: 9

Sitansu
Sitansu

Reputation: 3329

suppose you use an enum instead of a class if you know the number of instances in advance.

Enum use to serve as a type of fixed number of constants :

Eg.

public enum TodoDao {
    INSTANCE
};

INSTANCE is public static final fields of TodoDao class, and like all static fields they can be accessed by class name like

TodoDao b1 = TodoDao.INSTANCE;

Here INSTANCE is final static inner classes .

Read more:What's the use of "enum" in Java?

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

It's not a keyword. It's an enum constant, which should be in caps. You should be able to find that wherever you are learning Java from.

It's actually a really bad idea to have mutable statics like this. Also returning a mutable internal object is bad.

Upvotes: 3

Related Questions