Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the final keyword necessary in the Java singleton class?

Tags:

java

singleton

public class MySingleton{
  private static final MySingleton INSTANCE = new MySingleton();
  private MySingleton(){}
  public static getInstance(){
    return INSTANCE;
  }
}

Is this the right way to implement a Singleton. If yes then what is the necessity of the final keyword ?

like image 273
SRH LABS Avatar asked Dec 13 '12 23:12

SRH LABS


People also ask

Is singleton class is final in Java?

Singleton classes, if properly implemented, do not need to be declared final in order to not be extended. Since all the constructors of the singleton class are private, you can't extend that class. In fact, singleton classes are effectively final.

What are the rules for singleton class in Java?

In Java, Singleton is a design pattern that ensures that a class can only have one object. To create a singleton class, a class must implement the following properties: Create a private constructor of the class to restrict object creation outside of the class.

What are the necessary elements of the Singleton design pattern?

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.

Why do we need final keyword in Java?

In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.


1 Answers

Final will ensure the instance is not changeable after creation. If you're only including a constructor, and no setters, it's not a big deal. No one can change your INSTANCE and you are not changing it.

Not a bad idea to leave it there in case the class is later changed. Immutability offers some advantages (easier serialization, insurance against someone changing your object behind your back, etc).

It is harder to put immutability back in than it is to take it out. Write your code defensively so no one can mess it up later.

like image 143
Foo Avatar answered Oct 23 '22 03:10

Foo