接口类

2017-11-25  本文已影响0人  很很狠的狠角色
class Employee implements Comparable<Employee>
{
public int compareTo(Employee other){
return Double.compare(salary,other.salary);
}
}

对象克隆

Cloneable接口的出现与接口的正常使用没有任何关系。接口在这里只是作为一个标记,表明类的设计者知道要进行克隆处理。如果一个对象需要克隆,而没有实现Cloneable接口,就会产生一个已检测异常。
即使clone的默认实现(浅拷贝)能够满足需求,也应该实现Cloneable接口,将clone重定义为public,并调用super.clone()。

class Employee implements Cloneable
{
//raise visibility level to public,change return type
public Employee clone() throws CloneableSupportedException
{
return (Employee) super.clone();
}
}

为了实现深拷贝,必须克隆所有可变的实例域。

class Employee implements Cloneable{
public Employee clone() throws CloneNotSupportedException{
//call Object.clone()
Employee cloned = (Employee) super.clone();
//clone mutable fields
cloned.hireDay = (Date) hireDay.clone();
return cloned;
}
}
上一篇 下一篇

猜你喜欢

热点阅读