Exception in thread "main" java.lang.CloneNotSupportedException: com.wht.demo.Employee
at java.lang.Object.clone(Native Method)
at com.wht.demo.Employee.main(Employee.java:17)
如果clone的对象没有实现Cloneable 接口,就会报上面错误。
这个不是关键,这个设计思想更重要,用接口来限制类定义,虽然很简单,但是又了统一的规则,这些类就具有了安全可靠性。
package java.lang;
public interface Cloneable {
}
看下这个接口是不是很奇葩,全空什么都没有,但是它就是一个标志,规则。
具体使用实例如下:
package com.wht.demo;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
/**
* 员工类
*
* @author wht
*/
public class Employee implements Comparable<Employee> , Cloneable {
public static void main(String[] args) throws CloneNotSupportedException {
Employee employee1 = new Employee("JK",20000,2019,10,22);
System.out.println(employee1.getSalary());
Employee employee2 = (Employee) employee1.clone();
System.out.println(employee2.getSalary());
employee2.raiseSalary(200);
System.out.println(employee2.getSalary());
System.out.println(employee1.getSalary());
}
private Date hirDay;
private String name;
private double salary;
public Employee(String name, double salary, int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
this.name = name;
this.salary = salary;
this.hirDay = calendar.getTime();
}
@Override
public int compareTo(Employee o) {
if (this.salary < o.salary) {
return -1;
}
if (this.salary > o.salary) {
return 1;
}
return 0;
}
public Date getHirDay() {
return hirDay;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
@Override
public int hashCode() {
return Objects.hash(name, salary);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Double.compare(employee.salary, salary) == 0 &&
Objects.equals(name, employee.name);
}
@Override
public String toString() {
return "Employee{" +
"hirDay=" + hirDay +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
public void raiseSalary(double percent) {
this.salary += this.salary * percent / 100;
}
}