作者eliang ()
看板java
标题[问题] Cloneable 和 Object.clone()
时间Thu Dec 23 23:33:57 2010
官方文件对 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
1F:推 maokejackson:你去看Object.clone(),里面应该有throw Exception 12/24 01:30
2F:→ sbrhsieh:第一句话就没做到了:Invoking Object's clone method 12/24 09:17
所以我的结论是对的?
要建立一个可复制的类别, 只需覆写 Object.clone() 就好了,
不需 implements Cloneable,
所以 Cloneable 除了可以让人清楚知道某类别可否复制之外,
就没有其他功能?
※ 编辑: eliang 来自: 219.87.16.194 (12/24 10:58)
3F:→ H45:请注意 Object 的成员定义: protected Object clone() ... 12/24 11:21
4F:→ H45:简言之还是二楼所说的那样,你的程式没写对。 12/24 11:24