[問題] Cloneable 和 Object.clone()
官方文件對 Cloneable 這樣說明:
Invoking Object's clone method on an instance that does not implement
the Cloneable interface results in the exception CloneNotSupportedException
being thrown.
引用來源:
http://download.java.net/jdk7/docs/api/index.html?java/lang/Cloneable.html
意思應該是若某個類別宣告後面沒有 "implements Cloneable" 的字樣,
去呼叫該類物件的 clone() 就會產生 CloneNotSupportedException 例外,
但我做了個實驗:
class Foo // 沒接 implements Cloneable
{
public int member;
public Foo(int m)
{
member = m;
}
@Override // 但有覆寫 Object.clone()
public Foo clone()
{
return new Foo(member);
}
}
public class Main
{
public static void main(String[] args)
{
Foo f1 = new Foo(123);
Foo f2 = f1.clone();
System.out.println(f2.member);
}
}
結果可正常執行, 沒產生例外, 跟官方文件說的不一樣,
所以結論是 Cloneable 只是個標註而已?
標註給人看, 讓人知道那個類別可複製的而已?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.45.171.69
推
12/24 01:30, , 1F
12/24 01:30, 1F
→
12/24 09:17, , 2F
12/24 09:17, 2F
所以我的結論是對的?
要建立一個可複製的類別, 只需覆寫 Object.clone() 就好了,
不需 implements Cloneable,
所以 Cloneable 除了可以讓人清楚知道某類別可否複製之外,
就沒有其他功能?
※ 編輯: eliang 來自: 219.87.16.194 (12/24 10:58)
→
12/24 11:21, , 3F
12/24 11:21, 3F
→
12/24 11:24, , 4F
12/24 11:24, 4F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):