java - 014 - clone

2016-04-18  本文已影响12人  离子来了

java对象的复制

1.实现Cloneable协议

public  Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
public class test {
    public static void main(String[] args) throws Exception {
        Person p =new Person(41,"lisi");
        System.out.println(p);
    System.out.println(p.clone());//输出结果一样
}
}
class Person extends Object implements Cloneable{
    int age = 20;
    String name = "zhangsan";
    Person(int age ,String name){
            this.age = age;
                this.name = name;
    }
    public String toString(){
        return "name:" + this.name + "age:" + this.age;
    }
    public  Object clone() throws CloneNotSupportedException{
        return super.clone();
    }   
}
上一篇 下一篇

猜你喜欢

热点阅读