Use of private constructor to prevent instantiation of class?
You could add a private constructor, but there are two other options.
In the same situation I would use an enumerator. If it makes sense to your implementation, you could use that instead, if it's public
or private
depends on where you need to use it:
public enum MyStrings {
ONE ("something"),
TWO ("something else");
private String value;
private MyStrings(String str) {
this.value = str;
}
}
Another option would be to put it in an abstract
class, those can not be instantiated:
public abstract MyStrings {
public static final String STUFF = "stuff";
public static final String OTHER = "other stuff";
}
Access for both enumerator and abstract class works just like with the implementation you presented:
MyStrings.STUFF
For me the best explanation is in Effective Java book: Item 4: Enforce noninstantiability with a private constructor (See more)
In Summary:
- Private constructor is due utility classes were not designed to be instantiated, so is a design decision. (NO performance or memory overhead)
- Making a class abstract doesn't work because can be subclassed and then instantiated.
- With an abstract class the user may think the class is for inheritance.
- The only way to ensure no instantiation is to add a
private constructor
which ensures the default constructor is not generated. - Private constructor prevents inheritance because the super constructor cannot be called (so it is not need the declare the class as final)
- Throw an error in the private constructor avoids call it within the class.
Definetively, the best way would be something like next:
public class MyStrings {
private MyStrings () {
throw new AssertionError();
}
...
}
Use of private constructor to prevent instantiation of class?
There are several ways you can think of users preventing from the Instantiations for the purpose of creating the Constants
- As you have mentioned a class with the private Constructors and has all the string constants, is one way, even there is an overhead, that can be negligible
- Else you can create a Class with Final Modifier and Define your string constants
- You can use the Abstract Class with the String Constants
- You can define the string constants in the properties files and can access from that, this will definitely reduce the memory and increase the flexibility of your code.