DEV Community

Rajitha Prashan
Rajitha Prashan

Posted on

6

Keeping A Constructor Private

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 pattern example

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
just1602 profile image
Justin Lavoie

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.

Collapse
 
dehigas profile image
Rajitha Prashan

Thanks for the Tip! :D

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more