当在Java中使用协变返回类型时,javap中的Object.clone()

时间:2017-05-11 05:26:10

标签: java javap covariant-return-types

我正在阅读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.cloneSuper时,为什么会在Subjavap -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;
} 

1 个答案:

答案 0 :(得分:0)

clone方法属于类Object我们可以覆盖此方法。但是为了调用此方法,Java Runtime要求我们指示此类将使用克隆方法克隆其对象,该方法使得字段为字段该类实例的副本。

使用标记接口Cloneable完成此指示购买(标记接口没有任何方法,它们仅用于指示编译器和JVM的特定事物)。

在类超级clone()方法中,您调用super.clone()这只是对Object.clone()方法的调用,因为Object是Super的直接超类。

这解释了您在使用java.lang.Object clone()

时看到javap的原因

了解更多信息

Cloneable ref

相关问题