7

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;
    } 
} 
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
user1050619
  • 19,822
  • 85
  • 237
  • 413

3 Answers3

9

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.

Community
  • 1
  • 1
GeertPt
  • 16,398
  • 2
  • 37
  • 61
3

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
1

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?

Community
  • 1
  • 1
Sitansu
  • 3,225
  • 8
  • 34
  • 61