「Java」ジェネリクスクラスとワイルドカードにextends制限をつける

2022年3月16日

環境
JDK1.8
Eclipse 2019

書式
1.ジェネリクスクラスの定義
class クラス名<T> {処理コード}

2.ワイルドカード(?)にextendsを付ける
クラス名<? extends Integer> 変数 = new クラス名<>(Integer型数値);
ジェネリクスは、extendsを使用してIntegerクラスまたはIntegerのサブクラスを指定しています

クラス名<? extends Number> 変数= new クラス名<>(Number型数値);
ジェネリクスは、extendsを使用してNumberクラスまたはNumberのサブクラスを指定しています

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.Test;
//ジェネリクスクラスの定義
class TestAA<T> {
T tA;
// コンストラクタ
public TestAA(T tt) {
this.tA = tt;
}
// メソッドgetFunc
public T getFunc() {
return tA;
}
}
public class WildExtendsDemo {
public static void main(String[] args) {
// extends Integer
TestAA<? extends Integer> ttA = new TestAA<>(123);
// extends Number
TestAA<? extends Number> ttB = new TestAA<>(45.89);
System.out.println(ttA.getFunc());
System.out.println(ttB.getFunc());
}
}
package com.arkgame.Test; //ジェネリクスクラスの定義 class TestAA<T> { T tA; // コンストラクタ public TestAA(T tt) { this.tA = tt; } // メソッドgetFunc public T getFunc() { return tA; } } public class WildExtendsDemo { public static void main(String[] args) { // extends Integer TestAA<? extends Integer> ttA = new TestAA<>(123); // extends Number TestAA<? extends Number> ttB = new TestAA<>(45.89); System.out.println(ttA.getFunc()); System.out.println(ttB.getFunc()); } }
package com.arkgame.Test;

//ジェネリクスクラスの定義
class TestAA<T> {
      T tA;

      // コンストラクタ
      public TestAA(T tt) {
            this.tA = tt;
      }

      // メソッドgetFunc
      public T getFunc() {
            return tA;
      }

}

public class WildExtendsDemo {

      public static void main(String[] args) {
            // extends Integer
            TestAA<? extends Integer> ttA = new TestAA<>(123);
            // extends Number
            TestAA<? extends Number> ttB = new TestAA<>(45.89);

            System.out.println(ttA.getFunc());
            System.out.println(ttB.getFunc());

      }

}

実行結果
123
45.89

Java

Posted by arkgame