DESKTOP-7HC873M_20200903-李宗宝
问题
枚举类不能通过new关键字来产生对象
因为枚举类的构造方法默认都是私有的
public enum Sun {
/* public static final Sun SINGLETON = new Sun() ; */
SINGLETON ;
private Sun() {
// 注意,这里不要显式书写super(),因为编译器会补充这里的代码
System.out.println( "Sun无参构造执行" );
}
}
public class SunTest {
public static void main(String[] args) {
Sun s = Sun.SINGLETON ;
System.out.println( s );
Sun x = Sun.SINGLETON ;
System.out.println( x );
System.out.println( s == x );
}
}
Sun s = Sun.SINGLETON ;
这行代码执行时会跳转到
SINGLETON ;
相当于
public static final Sun SINGLETON = new Sun() ;
所以Sun的构造方法会执行
心得
国庆节真的就不能放个假吗!!!!我老妈想我了!!!!!!!!
近期评论