DEV Community

Tin Trinh
Tin Trinh

Posted on

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)