DEV Community

Tin Trinh
Tin Trinh

Posted on

3 2

Effective Java Part 4 - Enforce noninstantiability with a private constructor

When to use this?
When you want to create a class to hold bunch of static fields or static method. And you don't want to create any instance of the class.

To prevent making object from class we could mark the class as abstract but this would make the class looks like it mean to be inherited by other subclass and those subclass could be instantiated.

So the best way to enforce the noninstantiability is create an private constructor for the class.

class A {
    private A() {}
}

Even better but not strictly required, an exception could be throw if the constructor will be called setting would help to prevent unexpected call to the constructor from inside of the class

class A {
    private A() {
        throw new AssertError();
    }
}

Top comments (0)

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay