clone方法
定义一个student类,创建一个对象,用clone克隆对象
- clone方法只适用于自己类里面进行打点调用,在其他类里面打点调用clone方法,
- 需要将clone方法写出,如果有异常,还需要进行异常处理
- 1、自定义的类,使用clone方法,当前类必须要实现Cloneable接口
- 如果不实现接口,则会抛出异常,java.lang.CloneNotSupportException
- 2、因为object类的clone是protected修饰的,要重写此方法
- 才能在不同包中访问,把访问修饰符定义为public
- 3、Cloneable接口中没有方法,是一个标识性的接口,
- 针对object类的clone方法的实现
- 4、浅拷贝:引用变量拷贝的是地址,所有克隆的对象改变了对象的属性,原对象的属性也发生改变
- 5、深拷贝:引用变量拷贝一份对象,克隆对象的属性改变,原对象的属性不发生变化
DemoClone.java
package cn.tedu.demo;
/**
* 定义一个student类,创建一个对象,用clone克隆对象
* clone方法只适用于自己类里面进行打点调用,在其他类里面打点调用clone方法,
* 需要将clone方法写出,如果有异常,还需要进行异常处理
* 1、自定义的类,使用clone方法,当前类必须要实现Cloneable接口
* 如果不实现接口,则会抛出异常,java.lang.CloneNotSupportException
* 2、因为object类的clone是protected修饰的,要重写此方法
* 才能在不同包中访问,把访问修饰符定义为public
* 3、Cloneable接口中没有方法,是一个标识性的接口,
* 针对object类的clone方法的实现
* 4、浅拷贝:引用变量拷贝的是地址,所有克隆的对象改变了对象的属性,原对象的属性也发生改变
* 5、深拷贝:引用变量拷贝一份对象,克隆对象的属性改变,原对象的属性不发生变化
* @author cll
*
*/
public class DemoClone {
public static void test1() throws CloneNotSupportedException {
//浅拷贝,下面是浅拷贝的内容
/*Student stu=new Student();
stu.setAge(18);
System.out.println(stu.getAge());
Professor p=new Professor();
p.setAge(20);
stu.setP(p);
Student stu2=(Student)stu.clone();
stu2.setAge(19);
System.out.println(stu2.getAge());
stu2.getP().setAge(30);
System.out.println("------");
System.out.println(stu2.getP().getAge());*/
//深拷贝
//需要将Professor也进行clone方法的使用,还有实现Cloneable接口
Student stu=new Student();
stu.setAge(18);
//System.out.println(stu.getAge());
Professor p=new Professor();
p.setAge(28);
//System.out.println(p.getAge());
stu.setP(p);
System.out.println(stu.getP().getAge());
System.out.println(stu.getAge());
Student stu2=(Student)stu.clone();
//System.out.println(stu2.getAge());
stu2.setAge(19);
//System.out.println(stu2.getAge());
stu2.getP().setAge(38);
System.out.println("------");
System.out.println(stu.getP().getAge());
System.out.println(stu2.getP().getAge());
}
public static void main(String[] args) throws CloneNotSupportedException {
test1();
}
}
Student.java
package cn.tedu.demo;
public class Student implements Cloneable{
int age;
Professor p;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Professor getP() {
return p;
}
public void setP(Professor p) {
this.p = p;
}
@Override
public Object clone() throws CloneNotSupportedException {
// 深拷贝 访问修饰符可以改为public
Student stu=(Student)(super.clone());
stu.p =(Professor)this.p.clone();
return stu;
//浅拷贝 访问修饰符是 protected
/*return super.clone();*/
}
}
Professor.java
package cn.tedu.demo;
public class Professor implements Cloneable{
int age;
Professor p;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Professor getP() {
return p;
}
public void setP(Professor p) {
this.p = p;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}