This is the 13th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
preface
This article shows how private constructors can help make classes uninstantiable. It is important to pay attention to this point when you write your own tool class, do not think that there is no constructor without a constructor!!
Problems with the default constructor
Sometimes you want to provide classes that only contain static methods and static fields, such as some utility classes that we don’t want to instantiate, and instances don’t mean anything to it. Such as java.util.math.
However, in the absence of an explicit constructor, the compiler automatically provides a public, parameterless default constructor, which is often seen in the apis we provide, and can be incorrectly instantiated if the user does not understand it.
For example, we can see this happening in the decompiled code in Hutool.
It’s also not realistic to try to make this class abstract, because there’s a chance that the user will think that your class is only accessible by inheritance, and they’ll kuang kuang the whole subclass, and they’ll instantiate it
The solution
The simplest and most straightforward way to do this is to have the class include an explicit private constructor.
// Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass(a) {
throw new AssertionError();
}
// Remainder omitted
}
Copy the code
You can make an object uninstantiable by making a constructor method private by making the constructor method access identifier private.
Note the AssertionError in the private constructor, which prevents the instantiation constructor from being called inside the class, or from being called by the user through reflection. But it’s usually not written by anyone, so you can look at the code in the Math package, and there’s no throw Error.
You can see it’s big there don’t let anyone instantiate this class.
Side effects
This approach has the side effect of making it impossible for a class to be subclassed. Because all constructors must explicitly or implicitly call the superclass’s constructor, in which case there is no superclass constructor call that the subclass can access, since the sole constructor of the superclass is also private.