The class can be subclassed and the subclass instantiated.Futhermore,it misleads the user into thinking the class was designed for inheritance(继承). There is,however,a simple idiom to ensure noninstantiability.A default constructor is generated only if a class contains no explicit constructors,so a class can be made noninstantiable by including a private constructor.
package noninstantiability; //Noninstantiable utility class public class UtilityClass { //Suppress default constructor for noninstantiability private UtilityClass(){ throw new AssertionError(); } }
时间: 2024-11-10 07:41:01