In terms of inheritance,
When Class A has a private constructor, this private constructor is accessible only to those who have access to A’s private methods.
A’s inner classes and if A is an inner class of some class S, other inner classes of S have access to the private constructor.
So, A can be inherited by its own inner classes or S’s other inner classes.
To Achieve Singleton Pattern,
Singleton Pattern means that a single class is responsible for creating an object while making sure that only a single object gets created.
So to achieve this, the constructor must be private.
Singleton class creation
public class SingletonObject {
private static SingletonObject singletonObject = new SingletonObject();
// make the constructor private so that this class cannot be
// instantiated
private SingletonObject() {
}
// Get the only object available
public static SingletonObject getInstance() {
return singletonObject;
}
public void showMessage() {
System.out.println("Singleton Pattern");
}
}
Get object from singleton class
public class SingletonPatternEx {
public static void main(String[] args) {
//Get the only object available
SingletonObject object = SingletonObject.getInstance();
//show the message
object.showMessage();
}
}
Output
Singleton Pattern
Top comments (2)
The downside with this version of the singleton is it is not testable. You can't inject a mock to replace the
SingletonObject
. A good way to avoid this is to use the testable singleton pattern.Thanks for the Tip! :D