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およびで行っていることです)、 およびを実行すると、それぞれinおよびがSub表示されるのはなぜですか?Object.cloneSuperSubjavap -p Super.classjavap -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;
}