Java 常用類庫 之 對象的克隆 Cloneable

http://www.verejava.com/?id=16993097143799

/**
    知識點: 對象的克隆 Cloneable
*/
public class TestClone {
    
    public static void main(String[] args) throws Exception {
        //實例化一隻 喜洋洋
        Sheep sheep = new Sheep("喜洋洋", "白色");

        //灰太狼 想克隆兩隻 喜洋洋 就可以大吃一頓
        Sheep s1 = (Sheep) sheep.clone();
        Sheep s2 = (Sheep) sheep.clone();

        //輸出克隆的兩種羊
        System.out.println(s1.getName());
        System.out.println(s2.getName());
    }
}

class Sheep implements Cloneable {
    
    private String name;// 羊的名字
    private String color;//顏色

    public Sheep(String name, String color) {
        this.name = name;
        this.color = color;
    }

    public String getName() {
        return this.name;
    }

    public String getColor() {
        return this.color;
    }

    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

http://www.verejava.com/?id=16993097143799

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章