Enum 类的 clone() 方法抛出 CloneNotSupportedException。此方法可确保无法克隆枚举,这有助于维护其 "singleton" 属性。
用法
protected final Object clone() throws CloneNotSupportedException
覆盖
Enum 类的 clone() 方法覆盖了 Object 类的 clone() 方法。
返回值
clone() 方法不返回任何内容。
抛出
如果对象的类不支持 Cloneable 接口,则 clone() 方法会抛出 CloneNotSupportedException。覆盖此方法的子类也可以抛出 CloneNotSupportedException 异常以表明无法克隆实例。
例子1
import java.lang.*;
enum Colour{
Red,Pink,Black,Blue,White,red;
}
public class Enum_cloneMethodExample1 {
String Red;
public static void main(String[] args) {
Enum_cloneMethodExample1 enu = new Enum_cloneMethodExample1() {
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
};
Colour col = Colour.Red;
switch (col) {
case Red:
System.out.println("People with Red as their favourite colour are generally wiser.");
break;
case Blue:
System.out.println("People with Blue as their favourite colour are ambitious in life.");
break;
case Black:
System.out.println("People with Black as their favourite colour are soft hearted and are head strong.");
break;
case White:
System.out.println("Peoples with White as their favourite colour are benevolent and loving .");
break;
case Pink:
System.out.println("Peoples with Pink as their favourite colour are beautiful and intelligent.");
break;
}
}
}
输出:
People with Red as their favourite colour are generally wiser.
例子2
import java.lang.*;
enum Vehicle{
MarutiI(2010), MarutiII(2013),MarutiIII(2016);
int model;
Vehicle(int m) {
model = m;
}
int showModel() {
return model;
}
}
public class Enum_cloneMethodExample2 {
public static void main(String[] args) {
System.out.println("Maruti Car models till yet:");
//Enums can never be cloned...
Object t = new Enum_cloneMethodExample2() {
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
};
for(Vehicle m:Vehicle.values()) {
System.out.println(m + " launched in " + m.showModel() + " year.");
}
}
}
输出:
Maruti Car models till yet: MarutiI launched in 2010 year. MarutiII launched in 2013 year. MarutiIII launched in 2016 year.
相关用法
- Java Enum clone()用法及代码示例
- Java Enum compareTo()用法及代码示例
- Java Enum equals()用法及代码示例
- Java Enum toString()用法及代码示例
- Java Enum ordinal()用法及代码示例
- Java Enum valueOf()用法及代码示例
- Java Enum hashCode()用法及代码示例
- Java Enum finalize()用法及代码示例
- Java Enum name()用法及代码示例
- Java Enum getDeclaringClass()用法及代码示例
- Java EnumSet range()用法及代码示例
- Java EnumMap remove()用法及代码示例
- Java EnumMap hashCode()用法及代码示例
- Java EnumMap get()用法及代码示例
- Java EnumSet complementOf()用法及代码示例
- Java EnumSet clone()用法及代码示例
- Java EnumMap entrySet()用法及代码示例
- Java EnumMap containsKey()用法及代码示例
- Java EnumMap containsValue(value)用法及代码示例
- Java Enumeration asIterator()用法及代码示例
注:本文由纯净天空筛选整理自 Java Enum clone() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。