java深拷贝和浅拷贝

java浅拷贝的格式:

<pre name="code" class="java">public class A implements Cloneable{

	public Object clone(){
		try{
			return super.clone();
		}
		catch(CloneNotSupportedException e){
			return null;
		}
	}
        ……
}

 

深拷贝

public class A implements Cloneable{

	public Object clone(){
		try{
                        A copy = (A)super.clone();
                        copy.mutable = (mutable 类型)mutable.clone();
		        return copy;
		}
		catch(CloneNotSupportedException e){
			return null;
		}
	}
        ……
}
如下我建立了一个Employee类。

package Employee;

import java.util.Date;
import java.util.GregorianCalendar;

public class Employee implements Cloneable{

	public Object clone(){
		try{
			//Employee copy = (Employee)super.clone();
			//copy.hireday = (Date) hireday.clone();
			//return copy;
			return super.clone();
		}
		catch(CloneNotSupportedException e){
			return null;
		}
	}
	public Employee(String name,int salary) {
		this.name = name;
		this.salary = salary;
		//this.hireday = new GregorianCalendar(year,month-1,day).getTime();
	}
	public void setName(String name){
		this.name = name;
	}
	public void setHireday(int year,int month,int day){
		this.hireday = new GregorianCalendar(year,month-1,day).getTime();
	}	

	public void raiseSalary(double percent){
		salary = salary * (1 + percent/100);
	}
	
	public String getName(){
		return this.name;
	}
	public double getSalary(){
		return this.salary;
	}
	public Date getHireday(){
		return this.hireday;
	}
	private String name;
	private double salary;
	private Date hireday;

}
主函数是:

package Employee;

public class Main {

	public static void main(String[] args) {
		Employee John = new Employee("John",10000);
		John.setHireday(2016,3,18);
		Employee copyJohn = (Employee)John.clone();		
		John.setHireday(2015,1,1);
		John.raiseSalary(100);
		
		System.out.println("原类的招聘时间:"+John.getHireday());
		System.out.println("克隆类的招聘时间"+copyJohn.getHireday());		
		System.out.println("原类的工资:     "+John.getSalary());
		System.out.println("克隆类的工资:"+copyJohn.getSalary());
	
	}
	
}

按理说这是一个浅拷贝,应该会返回null,但是返回结果如下:

不是很明白。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值