Scene:
When creating tool classes, most of them do not have to be instantiated, and instantiation does not make sense to them.in this case, create the class to make sure that it is not instantiated.
A problem exists:While creating a class that cannot be instantiated, there is no constructor defined. However, the client can still instantiate the class when it is used. The client can inherit the class and instantiate it by instantiating its subclasses; The client can invoke the default constructor to instantiate the class.
to avoid this problem, use the method of defining a private constructor:
public class Utilityclass { //Suppress default constructor for noninstantiability private Utilityclass () { throw new Assertionerror ();} }
Adding the throw new Assertionerror () is to avoid instantiating the Utilityclass class in Utilityclass. Because of the private parameterless constructor, there is no way for the client to invoke the default constructor to instantiate the class, or to avoid the instantiation of the inherited subclass. Like what:
public class Utilityclass { //Suppress default constructor for noninstantiability private Utilityclass () { throw new Assertionerror (); } public static Utilityclass getinstance () { return new Utilityclass ();} } public class Test {public static void Main (string[] args) { Utilityclass one = Utilityclass. getinstance (); }}
after the above code is executed, the following error is reported:Exception in thread "main" Java.lang.AssertionErrorAt org.effectivejava.examples.chapter02.item04.utilityclass.<init> (Utilityclass.java:8)At org.effectivejava.examples.chapter02.item04.UtilityClass.getInstance (utilityclass.java:13)At Org.effectivejava.examples.chapter02.item04.Test.main ( Test.java:9)Adding the throw new Assertionerror () can successfully avoid instantiating the Utilityclass class in Utilityclass.
You can successfully avoid the following code execution:
public class Subutilityclass extends Utilityclass {}
When attempting to inherit the class, the following error is prompted: Implicit Super constructor Utilityclass () is not visible for default constructor. Must define an explicit Constructorimplicit Super constructor Utilityclass () are not visible for default constructor. Must define an explicit constructor client also cannot invoke the default constructor.
public class Test {public static void Main (string[] args) { //Utilityclass one = new Utilityclass ();} }
Item 4----Ability to harden non-instancing through private constructors