java.lang.CloneNotSupportedException: cloneTest.Employee

一、报错记录
java.lang.CloneNotSupportedException: cloneTest.Employee
	at java.lang.Object.clone(Native Method)
	at cloneTest.Employee.clone(Employee.java:19)
	at cloneTest.Test.main(Test.java:9)

怼代码

package cloneTest;

import java.util.Calendar;
import java.util.Date;

public class Employee {
     
    private String name;
    private double salary;
    private Date hireDay;

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

    @Override
    public Employee clone() throws CloneNotSupportedException {
     
        Employee cloned = (Employee) super.clone();
        cloned.hireDay = (Date) hireDay.clone();
        return cloned;
    }

    public void raiseSalary(double byPercent) {
     
        double raise = salary * byPercent / 100;
        salary += raise;
    }

    public String getName() {
     
        return name;
    }

    public void setName(String name) {
     
        this.name = name;
    }

    public double getSalary() {
     
        return salary;
    }

    public void setSalary(double salary) {
     
        this.salary = salary;
    }

    public Date getHireDay() {
     
        return hireDay;
    }

    public void setHireDay(int year, int month, int day) {
     
//        Date newHireDay = new GregorianCalendar(year, month-1, day).getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month-1, day);
        hireDay.setTime(calendar.getTime().getTime());
    }

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

package cloneTest;

public class Test {
     
    public static void main(String[] args) {
     
        Employee original = new Employee("John Q. Public", 50000);
        original.setHireDay(2020, 1, 1);

        try {
     
            Employee copy = original.clone();
            copy.raiseSalary(10);
            copy.setHireDay(2000, 1, 1);
            System.out.println(original);
            System.out.println(copy);
        } catch (CloneNotSupportedException e) {
     
            e.printStackTrace();
        }
    }
}

Employee不支持clone,这个类有clone方法,并且加上了@Override,编译器也没有报错。不继承Cloneable接口,clone方法重写的谁的?IDEA的问题吗难道,换MyEclipse试试看。
java.lang.CloneNotSupportedException: cloneTest.Employee_第1张图片
没差别,给clone换个方法名f,就有红色的波浪线
java.lang.CloneNotSupportedException: cloneTest.Employee_第2张图片

二、小记

慢慢探索、深入,争取写出点有意义的东西。测试什么功能的接口,先继承了,省得覆盖方法写了,编译器也没提示,就测试不通过。

你可能感兴趣的:(JAVA)