java, lang Cloneable interface °接口 java. lang Cloneable是一个标记接口 WM将对实现了 java. lang Cloneable接口并且 提供了 publick的lone)方法的类的对象提住 复制支持 ess类名> implements Cloneable 999 public Object cloneD oo.)
java.lang.Cloneable Interface • 接口java.lang.Cloneable是一个标记接口 • JVM将对实现了java.lang.Cloneable接口并且 提供了public的clone()方法的类的对象提供 复制支持 class <类名> implements Cloneable{ // …… public Object clone() { … } }
class Sheep implements Cloneable( private string name; private float weight private string color, public Sheep(string name, float weight, String color) this name=name: this weight-weight; this color=color; public Object cloned return superclone; 3 catch(CloneNotSupportedExceptione)( 调 throw new InternalErroro Sheep sheep= new Sheep(“ XiaoBai”,45,“ White”); Sheep sheep b=sheep cloned;
Object.clone() Method • 类Object的clone()方法如下: protected Object clone() throws CloneNotSupportedExdeption • 实现了java.lang.Cloneable接口的类的对象调 用Object.clone()方法将返回当前对象的一个 影子拷贝(Shallow Copy),这个拷贝中所有 基本数据类型的域与源对象相同 class Sheep implements Cloneable{ private String name; private float weight; private String color; public Sheep(String name,float weight,String color){ this.name=name; this.weight=weight; this.color=color; } public Object clone(){ try{ return super.clone(); } catch(CloneNotSupportedException e) { throw new InternalError(); } } } Sheep sheepA=new Sheep(“XiaoBai”,45, “White”); Sheep sheepB=sheepA.clone();
public class IntegerStack implements Cloneable( private int[ buffer; private int top public IntegerStack(int maxSize b 29 buffer ou bb first 考 top: 1 publ buffer ret second top: 1 publ Ion return super clone; 国■加 IntegerStack first-=new IntegerStack (2); first push (2); first push(9); IntegerStack second=(IntegerStack)first clone(;
Shallow Clone • 方法Object.clone()只创建当前对象的影子拷 贝,把这个过程称为影子复制 • 影子复制是在复制过程中只把基本数据类型 的引用类型的值复制到新的对象中 • 源对象与其影子拷贝的基本数据类型的域具 有相同的值,当引用类型的域且共同引用相 同的对象 public class IntegerStack implements Cloneable{ private int[] buffer; private int top; public IntegerStack(int maxSize){ buffer=new int[maxSize]; top=-1; } public void push(int val){ buffer[++top]=val; } public int pop(){ return buffer[top--]; } public Object clone() throws CloneNotSupportedException{ return super.clone(); } } IntegerStack first=new IntegerStack(2); first.push(2); first.push(9); IntegerStack second=(IntegerStack)first.clone(); buffer top: 1 buffer top: 1 first second 2 9