当前位置: 技术问答>java相关
大家看看这个令人费解的问题
来源: 互联网 发布时间:2015-05-25
本文导语: public class Inter1 extends Object implements Cloneable{ private int a=0; private int b=0; private int c=0; public int get(){ return a; } public void set(int a){ this.a=a; } ...
public class Inter1 extends Object implements Cloneable{
private int a=0;
private int b=0;
private int c=0;
public int get(){
return a;
}
public void set(int a){
this.a=a;
}
public static void main(String[] args) throws CloneNotSupportedException {
Inter1 c=new Inter1();
Inter1 d;
c.set(9);
d=(Inter1)c.clone();
System.out.println(d.a);
System.out.println(d.b);
System.out.println(d.c);
}
}
结果为9
0
0
说明可以clone d,可是我仅仅只是继承了object的clone而已,并没有覆盖它,为什么直接调用基类的clone就可以复制子类对象?
private int a=0;
private int b=0;
private int c=0;
public int get(){
return a;
}
public void set(int a){
this.a=a;
}
public static void main(String[] args) throws CloneNotSupportedException {
Inter1 c=new Inter1();
Inter1 d;
c.set(9);
d=(Inter1)c.clone();
System.out.println(d.a);
System.out.println(d.b);
System.out.println(d.c);
}
}
结果为9
0
0
说明可以clone d,可是我仅仅只是继承了object的clone而已,并没有覆盖它,为什么直接调用基类的clone就可以复制子类对象?
|
Cloneable is only a mark interface.
if you override clone(), then even if you don't implement Cloneable, your clone code will still be executed.
But if you don't override clone, the default clone provided by jdk will check (this instanceof Cloneable).
If it is Cloneable, the clone() will do shallow copy for you. If it does not, exception will be thrown.
Overall, it's a bad hack adopted by JDK. Typical abuse of "instanceof". Ugly, isn't it?
if you override clone(), then even if you don't implement Cloneable, your clone code will still be executed.
But if you don't override clone, the default clone provided by jdk will check (this instanceof Cloneable).
If it is Cloneable, the clone() will do shallow copy for you. If it does not, exception will be thrown.
Overall, it's a bad hack adopted by JDK. Typical abuse of "instanceof". Ugly, isn't it?