zoukankan      html  css  js  c++  java
  • java clone 建立一个深拷贝

    简介

    clone 建立 深拷贝

    code

    核心代码

    	public Employee clone() throws CloneNotSupportedException{
    		Employee cloned = (Employee) super.clone();
    		cloned.hireDay = (Date) hireDay.clone();
    		return cloned;
    	}
    
    package cn;
    
    public class CloneTest {
    	public static void main(String[] args){
    		try{
    			Employee original = new Employee("John Q. Public", 50000);
    			original.setHireDay(2000, 1, 1);
    			Employee copy = original.clone();
    			copy.raiseSalary(10);
    			copy.setHireDay(2002, 12, 31);
    			System.out.println("origin=" + original);
    			System.out.println("copy = " + copy);
    		}
    		catch(CloneNotSupportedException e){
    			e.printStackTrace();
    		}
    	}
    }
    
    

    package cn;

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

    public class Employee implements Comparable, Cloneable {
    private String name;
    private double salary;
    private Date hireDay;

    public Employee(String name, double salary) {
    	this.name = name;
    	this.salary = salary;
    	hireDay = new Date();
    }
    
    public Employee clone() throws CloneNotSupportedException{
    	Employee cloned = (Employee) super.clone();
    	cloned.hireDay = (Date) hireDay.clone();
    	return cloned;
    }
    
    public void setHireDay(int year, int month, int day){
    	Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
    	hireDay.setTime(newHireDay.getTime());
    }
    
    public String getName(){
    	return name;
    }
    
    public double getSalary() {
    	return salary;
    }
    
    public void raiseSalary(double byPercent) {
    	double raise = salary * byPercent / 100;
    	salary += raise;
    }
    
    @Override
    public int compareTo(Employee other) {
    	// TODO Auto-generated method stub
    	return Double.compare(salary,  other.salary);
    }
    
    public String toString() {
    	return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
    }
    

    }

    
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    国内代码托管平台(Git和SVN)
    搭建网络svn实战
    2016你一定要试试这8款原型设计工具
    Linux下查看用户列表
    详解Oracle DELETE和TRUNCATE 的区别
    Oracle 用户表空间查看、修改大小、设置自增长等
    win7电脑定时开机设置方法
    weblogic负载分发
    怎样实现一个数据库关系系统?
    选择数据库管理系统(DBMS)时主要考虑的因素
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13474089.html
Copyright © 2011-2022 走看看