トップ 一覧 ping 検索 ヘルプ RSS ログイン

SJC-P 共変戻り値の変更点

  • 追加された行はこのように表示されます。
  • 削除された行はこのように表示されます。
!!!SJC-P 共変戻り値
!!共変戻り値(covariant return types)
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.5
*以前のバージョンでは許されていなかった
*オーバーライドの制限をゆるくする
以前のバージョンでオーバーライドをする場合、戻り値を含めシグネチャが完全に一致している必要があったが、Java5からは、戻り値については、オーバーライドされるメソッドの戻り値のサブクラスを戻すことが可能になった。
 package returntype;
 
 public class ConvariantReturnTypeTest1 {
 
     public static void main(String[] args) {
         ConvariantReturnTypeTest1 me = new ConvariantReturnTypeTest1();
         me.testReturnType();
     }
     public void testReturnType() {
         try {
             Base b1 = new Base(999);
             Base b2 = b1.clone();  // ダウンキャスト不要
             System.out.println(b2.id);
             
             Deriv d1 = new Deriv(888);
             Base  b3 = d1.clone();
             System.out.println(b3.id);
             
         } catch (CloneNotSupportedException e) {
             e.printStackTrace();
         }
     }
 }
 class Base implements Cloneable {
     protected int id;
     public Base(int id) {
         this.id = id;
     }
     // Object.clone() (戻り値はObject)をオーバーライドして、戻り値をサブクラスとできる
     protected Base clone() throws CloneNotSupportedException {
         return new Base(this.id);
     }
 }
 class Deriv extends Base {
     public Deriv(int id) {
         super(id);
     }
     protected Deriv clone() throws CloneNotSupportedException {
         return new Deriv(this.id);
     }
 }
----
{{amazon 4822282775}}
----
{{include_html banner_html, "!SJC-P"}}