CloneNotSupportedException

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;

  }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值