Effective Java article 4 strengthens the ability to be instantiated through private constructors

Strengthen the non-instantiable ability through the private constructor

Sometimes it may be necessary to write classes that only contain static methods and static fields, similar to java.lang.Math and java.util.Arrays, to organize basic types of values ​​or related methods on array types, similar to java.util The .Collections method organizes methods on objects that implement a specific interface, including factory methods.

Such a tool class does not want to be instantiated because it has no meaning, but in the absence of an explicit constructor, the compiler will automatically provide a public, no-parameter implicit constructor.

Attempting to define a class as an abstract class to force the class to not be instantiated is also unworkable. The class can still be subclassed, and subclasses can also be instantiated. Then, there is a simple way to ensure that the class is not instantiated, because only when the class does not contain an explicit constructor, the compiler will automatically generate an implicit no-argument constructor, so you only need to keep a private in the class The constructor can guarantee that it will not be instantiated.

public class FoodFactory{
    
    
    private FoodFactory{
    
    
       throw new AssertionError();
    }
	public static Food getFoodFactory(String arg1){
    
    
	...
	}
}

Since the explicit constructor is private, it is impossible to access it outside the class. AssertionError() is not necessary, but you can avoid accidentally calling the constructor internally. It can guarantee that it cannot be instantiated under any circumstances. This category.

This habit also has side effects. It prevents a class from being subclassed. All constructors must call the superclass constructor explicitly or by reference. In this case, the subclass has no accessible superclass constructor. Can be called.


Reference article: https://www.jianshu.com/p/17e10c460005

Guess you like

Origin blog.csdn.net/qq_38941937/article/details/115311616