package designpattern.prototype; public class singer implements cloneable { string name; int age; hotmusic hotmusic; public singer(string name, int age, hotmusic hotmusic) { super(); this.name = name; this.age = age; this.hotmusic = hotmusic; } 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 hotmusic gethotmusic() { return hotmusic; } public void sethotmusic(hotmusic hotmusic) { this.hotmusic = hotmusic; } @override protected object clone() throws clonenotsupportedexception { singer singerclone = (singer) super.clone(); singerclone.hotmusic = (hotmusic) hotmusic.clone();// 这一句,下面解释 return singerclone; } @override public string tostring() { return "singer [name=" + name + ", age=" + age + ", hotmusic=" + hotmusic + "]"; } }
package designpattern.prototype; public class hotmusic implements cloneable { string name; string date; public hotmusic(string name, string date) { super(); this.name = name; this.date = date; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getdate() { return date; } public void setdate(string date) { this.date = date; } @override protected object clone() throws clonenotsupportedexception { return super.clone(); } @override public string tostring() { return "hotmusic [name=" + name + ", date=" + date + "]"; } }
package designpattern.prototype; public class client { public static void main(string[] args) { singer singer1 = new singer("周杰伦", 40, new hotmusic("告白气球", "2016")); system.out.println(singer1); try { singer singer2 = (singer) singer1.clone(); singer2.hotmusic.setname("等你下课"); singer2.hotmusic.setdate("2018"); system.out.println("========================================================"); system.out.println(singer1); system.out.println(singer2); } catch (clonenotsupportedexception e) { e.printstacktrace(); } } }
singer [name=周杰伦, age=40, hotmusic=hotmusic [name=告白气球, date=2016]] ======================================================== singer [name=周杰伦, age=40, hotmusic=hotmusic [name=告白气球, date=2016]] singer [name=周杰伦, age=40, hotmusic=hotmusic [name=等你下课, date=2018]]
singer [name=周杰伦, age=40, hotmusic=hotmusic [name=告白气球, date=2016]] ======================================================== singer [name=周杰伦, age=40, hotmusic=hotmusic [name=等你下课, date=2018]] singer [name=周杰伦, age=40, hotmusic=hotmusic [name=等你下课, date=2018]]
如对本文有疑问, 点击进行留言回复!!
网友评论