62,616
社区成员
发帖
与我相关
我的任务
分享
class Person implements Cloneable{ // 实现Cloneable接口表示可以被克隆
private String name ;
public Person(String name){
this.name = name ;
}
public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
public Object clone() throws CloneNotSupportedException{ //覆写Object clone()方法
return super.clone();
}
};
public class CloneDemo01 {
public static void main(String args[]) throws Exception{
Person p1 = new Person("张三") ;
Person p2 = null ;
try{
p2 = (Person)p1.clone();
}
catch(Exception e){
}
}
};
/**
* A class implements the <code>Cloneable</code> interface to
* indicate to the {@link java.lang.Object#clone()} method that it
* is legal for that method to make a
* field-for-field copy of instances of that class.
* <p>
* Invoking Object's clone method on an instance that does not implement the
* <code>Cloneable</code> interface results in the exception
* <code>CloneNotSupportedException</code> being thrown.
* <p>
* By convention, classes that implement this interface should override
* <tt>Object.clone</tt> (which is protected) with a public method.
* See {@link java.lang.Object#clone()} for details on overriding this
* method.
* <p>
* Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
* Therefore, it is not possible to clone an object merely by virtue of the
* fact that it implements this interface. Even if the clone method is invoked
* reflectively, there is no guarantee that it will succeed.
*
* @author unascribed
* @version 1.17, 11/17/05
* @see java.lang.CloneNotSupportedException
* @see java.lang.Object#clone()
* @since JDK1.0
*/
public interface Cloneable {
}