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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。