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
  • 相关阅读:
    unity3d 随机生成地形之随机山脉
    unity3d ppsspp模拟器中的post processing shader在unity中使用
    unity3d shader之实时室外光线散射(大气散射)渲染
    Unity3d 游戏中的实时降噪-对Square Enix文档的研究与实现
    Unity3d 获取屏幕depth与normal
    unity3d Hair real time rendering 真实头发实时渲染
    java.net.URL类
    Springboot定时任务
    Base64编码
    ShiroUtil 对密码进行加密
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13474089.html
Copyright © 2011-2022 走看看