我正在阅读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()
inSuper
和所做的事情Sub
),为什么我分别在运行and时看到Object.clone
inSuper
和?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;
}