对于其中一段例题代码有一个疑问,如下所示:

最近在自学Introduction to Java Programming那本书,
package testOOP;

public class House implements Cloneable, Comparable {
private int id;
private double area;
private java.util.Date whenBuilt;

public House(int id, double area) {
this.id = id;
this.area = area;
whenBuilt = new java.util.Date();
}

public double getId() {
return id;
}

public double getArea() {
return area;
}

public java.util.Date getWhenBuilt() {
return whenBuilt;
}

/** Override the protected clone method defined in the Object
class, and strengthen its accessibility */
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException ex) {
return null;
}
}
/** Implement the compareTo method defined in Comparable */
public int compareTo(Object o) {
if (area > ((House)o).area)
return 1;
else if (area < ((House)o).area)
return -1;
else
return 0;
}
public static void main(String[] args)
{
House house1 = new House(1, 200.12);
House house2 = (House)house1.clone();
}
}
1,不明白的就是House类是Object类的子类那么就相应继承Protected native Object clone()这一方法,可为什么书上说必须覆盖此方法并将修饰符改为public以便任何包中均可使用?难道不改,House类的实例house1就不能使用吗?(在我删去覆盖的clone()方法后,Eclipse提示错误Unhandled exception type CloneNotSupportedException)
2,我不删去整个方法,只是删去try-catch块留下return super.clone()也是提示错误Unhandled exception type CloneNotSupportedException,这是为什么?

德玛西亚99
浏览 309回答 2
2回答

白板的微信

Object类的方法:protected native Object clone() throws CloneNotSupportedException;1、如果不实现clone,那么执行到House house2 = (House)house1.clone(); 会报错,因为House没有clone方法,不能克隆。将clone()修饰符改为public,是因为这样可以在外部调用house.clone(),否则重载就没有意义。2、如果去掉try...catch...,编译return super.clone();会报错,因为super.clone()定义时声明了异常,所以在调用时,必须捕获这个异常。如果不捕获,在House.clone()方法声明也可以:public Object clone() throws CloneNotSupportedException;这样,你在调用house.clone()时就必须try...catch...

倚天杖

e house2 = (House)house1.clone();&nbsp;要使用这个就必须实现cloneable接口,不实现就报错Object的现实是if(!this instanceof Cloneable){throw new CloneNotSupportedException();}
打开App,查看更多内容
随时随地看视频慕课网APP