Effective Java 英文 第二版 读书笔记 Item 4:Attempting to enforce noninstantiability by making a class abstract does not work.

 

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();
    }

    
}

 

posted @ 2015-09-04 16:13  郁闷紫番薯  阅读(171)  评论(0编辑  收藏  举报