Java.lang.Enum.clone() 方法
描述
java.lang.Enum.clone() 方法保证枚举永远不会被克隆,这是保持它们的"单例"状态所必需的。
声明
以下是 java.lang.Enum.clone() 方法的声明。
protected final Object clone() throws CloneNotSupportedException
参数
NA
返回值
此方法不返回任何值。
异常
CloneNotSupportedException − 如果对象的类不支持 Cloneable 接口。 覆盖 clone 方法的子类也可以抛出此异常,表示无法克隆实例。
示例
下面的例子展示了 java.lang.Enum.clone() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
// enum showing Mobile prices
enum Mobile {
Samsung(400), Nokia(250);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class EnumDemo {
public static void main(String args[]) {
System.out.println("Enums can never be cloned...");
EnumDemo t = new EnumDemo() {
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
};
System.out.println("CellPhone List:");
for(Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Enums can never be cloned... CellPhone List: Samsung costs 400 dollars Nokia costs 250 dollars

