我正在阅读covariant return types in Java.我写了以下代码:
父类:
package other;
public class Super implements Cloneable {
@Override
public Super clone() throws CloneNotSupportedException {
return (Super) super.clone();
}
}
儿童班:
package other;
public class Sub extends Super {
@Override
public Sub clone() throws CloneNotSupportedException {
return (Sub) super.clone();
}
}
我如何使用它:
package com.sample;
import other.Sub;
import other.Super;
public class Main {
public static void main(String[] args) throws Exception {
Super aSuper = new Super();
Super bSuper = aSuper.clone();
System.out.println(aSuper == bSuper); // false
Sub aSub = new Sub();
Sub bSub = aSub.clone();
System.out.println(aSub == bSub); // false
}
}
如果可以在覆盖方法时返回子类型(如您所见,这是我在clone()
和Super
中对Sub
的处理方式) ,当我分别运行Object.clone
和Super
时,为什么会在Sub
和javap -p Super.class
中看到javap -p Sub.class
?
javap -p Super.class
的结果:
Compiled from "Super.java"
public class other.Super implements java.lang.Cloneable {
public other.Super();
public other.Super clone() throws java.lang.CloneNotSupportedException;
public java.lang.Object clone() throws java.lang.CloneNotSupportedException;
}
javap -p Sub.class
的结果:
Compiled from "Sub.java"
public class other.Sub extends other.Super {
public other.Sub();
public other.Sub clone() throws java.lang.CloneNotSupportedException;
public other.Super clone() throws java.lang.CloneNotSupportedException;
public java.lang.Object clone() throws java.lang.CloneNotSupportedException;
}
答案 0 :(得分:0)
clone方法属于类Object
我们可以覆盖此方法。但是为了调用此方法,Java Runtime要求我们指示此类将使用克隆方法克隆其对象,该方法使得字段为字段该类实例的副本。
使用标记接口Cloneable
完成此指示购买(标记接口没有任何方法,它们仅用于指示编译器和JVM的特定事物)。
在类超级clone()方法中,您调用super.clone()
这只是对Object.clone()方法的调用,因为Object是Super的直接超类。
这解释了您在使用java.lang.Object clone()
javap
的原因
了解更多信息