Clone方法

来源:互联网 发布:加拿大皇后大学gpa算法 编辑:程序博客网 时间:2024/05/30 04:24

clone方法返回对象的一个副本,两个对象不相等。即x.clone!=x;(内存不相等) x.clone.getclass=x.getclass(值相等)。clone是浅拷贝,对象里面的对象还是会捆绑,所以对象里面的对象也要写clone方法。对象要贴标签(implements clonable)才能clone 。clone 三部曲:1声明实现  (implements clonable)   2调用super.clone 拿到一个对象 (写clone函数)  3 把浅拷贝的引用只想原型对象新的克隆体

当要克隆的类中只有基础数据类型或者不可变的引用类型时只需 retrun super.clone();

而引用类型的变量会捆绑时,要用深clone。  Account a=(Account)super.clone(); if(user!=null){ a.user=(user)user.clone()}

就是对象里面的对象再克隆一边。这里要注意的是,每个对象都要贴标签,和写clone方法 我们看代码:

主类

package cn.hncu.clone;public class cloneDemo {public static void main(String[] args) {//浅克隆System.out.println("浅克隆");Person p=new Person("大浪B普郎东", 22);try {Person p1=(Person) p.clone();System.out.println(p.toString());System.out.println(p1.toString());System.out.println("----------");p.setName("大帅比东东");System.out.println(p.toString());System.out.println(p1.toString());} catch (CloneNotSupportedException e) {e.printStackTrace();}System.out.println("-----------------"+"\t\n"+"深克隆\t\n*****************");//深克隆Student s=new Student(p, 100);try {Student s1=(Student) s.clone();System.out.println(s.toString());System.out.println(s1.toString());System.out.println("************");s.setScore(88);System.out.println(s.toString());System.out.println(s1.toString());} catch (CloneNotSupportedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

Person类:

package cn.hncu.clone;public class Person implements Cloneable{private String name;private int age;public Person(String name, int age) {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;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}}

Student类:

package cn.hncu.clone;public class Student implements Cloneable{Person person;private int score;public Student(Person person, int score) {this.person = person;this.score = score;}@Overridepublic String toString() {return "Student [person=" + person + ", score=" + score + "]";}public Person getPerson() {return person;}public void setPerson(Person person) {this.person = person;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}@Overrideprotected Object clone() throws CloneNotSupportedException {Student s=(Student) super.clone();if(s!=null){s.person=(Person) person.clone();}return s;}}


0 0
原创粉丝点击