Object cloning in java

1. The clone method in the Object class is declared as protected, and the subclass can only call the protected clone method to clone its own object. You must redefine clone as public to allow all methods to clone objects.
2. All array types have a public clone method, not protected. You can use this method to create a new array that contains a copy of all the elements of the original array.

Below is the test case

package com.fu.demo;

import java.util.Date;

public class myclone {
    
    
    public static void main(String[] args) throws CloneNotSupportedException {
    
    
        employee a = new employee("a", 50000,new Date());
        a.setHireDay(2000,1,1);
       employee copy= (employee) a.clone();
      //  myclone copy=(myclone) new myclone().clone();
        //Object o=new Object();
      //Object t=o.clone();
       copy.raisesalary(10);
      copy.setHireDay(2002,12,31);
        System.out.println(a);
        System.out.println(copy);
       // System.out.println(new employee() instanceof Cloneable);
        //System.out.println(copy instanceof Cloneable);
    }

}
package com.fu.demo;

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

public class employee implements Cloneable{
    
    
    private String name;
    private double salary;
    private Date hireDay;

    public employee() {
    
    
    }

    public employee(String name, double salary, Date hireDay) {
    
    
        this.name = name;
        this.salary = salary;
        this.hireDay = hireDay;
    }


    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 newday=new GregorianCalendar(year,month-1,day).getTime();
        hireDay.setTime(newday.getTime());
    }
    public void raisesalary(double percent){
    
    
        double r=salary*percent/100;
        salary+=r;
    }

    @Override
    public String toString() {
    
    
        return "employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", hireDay=" + hireDay +
                '}';
    }
}





Guess you like

Origin blog.csdn.net/changbaishannefu/article/details/112310525