Java实现克隆一个对象

package com.wms;

public class HumanClone {

    public static void main(String[] args) {

        Human hm1 = new Human("张三",60);
        try {
            Human hm2 = (Human) hm1.clone();
            System.out.println(hm1);
            System.out.println(hm2);
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }

}
package com.wms;

public class Human implements Cloneable{

    private String name;
    private int age;
    public Human() {}
    public Human(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Human [name=" + name + ", age=" + age + "]";
    }
    
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    
}

 

posted @ 2016-02-02 10:37  sweetstar86  阅读(702)  评论(0编辑  收藏  举报