浅拷贝:指的是你的类本身被拷贝,而没有拷贝类本身属性中的类。
深拷贝:指的是包含类本身和属性类在内的所有类的拷贝。
简单点说:就是浅拷贝的两个对象中的属性还会指向同一个类,而深拷贝则全部单独了。也就是说深拷贝把关联关系也拷贝了。可以简单理解为深拷贝中的数据类型中含有类类型的变量,因为java中传递参数的形式是以传值方式进行的。以八种基本类型而言,传递的是具体值。而以引用类型,传递的是对象的引用。
本文主要举一下深拷贝的例子,代码如下:
package clonedemo;
public class Student implements Cloneable...{
private String name ;
private int age ;
teacher tea ;
Student(String name , int age,teacher tea)...{
this.name = name ;
this.age = age ;
this.tea = tea ;
}
Student()...{
}
void showInfo(String stu)...{
System.out.println(stu+ " : name ="+this.name) ;
System.out.println(stu+" : age ="+this.age) ;
System.out.println(stu+" : name ="+this.tea.getName()) ;
System.out.println(stu+" : age ="+this.tea.getAge()) ;
}
public Object clone()...{
//Object obj = null ;
Student obj = null ;
try ...{
obj = (Student)super.clone() ;
} catch (CloneNotSupportedException e) ...{
// TODO: handle exception
e.printStackTrace() ;
}