簡體   English   中英

實例化具有與其超類相同類型的泛型類型對象

[英]Instantiating a generic type object with the same type as its superclass

我想知道是否可以創建與它所包含的類具有相同類型的泛型類型的對象。

例如,考慮這個對象

public class Foo<T> {

   private T variable;

   Foo() {

   }
}

現在考慮這個

public class Bar<T> {

   private Foo foo;

   Bar() {
      foo = (T) new Foo();
   }
}

我希望 bar 類中的 foo 對象的數據類型與 bar 實例化的數據類型相同。

是的,你可以這樣做,它會起作用。 但是您需要有正確的重載構造函數來處理數據類型。

程序的輸出是:

class java.lang.Integer
class java.lang.String

如您所見, foo 變量的數據類型與 Bar 對象的數據類型相同。

而且您在程序中犯了一個錯誤,Bar 類中應該有一個重載的構造函數。

package test;

public class test {

    public static void main(String[] args) {
        Bar<Foo> integerBar = new Bar(3);
        Foo<Integer> fooIntegerObject = (Foo) integerBar.getFoo();

        Bar<Foo> stringBar = new Bar("hello");
        Foo<String> fooStringObject = (Foo) stringBar.getFoo();

        System.out.println(fooIntegerObject.getVariable().getClass());
        System.out.println(fooStringObject.getVariable().getClass());

    }
}

class Foo<T> {

    private T variable;

    Foo(T x) {
        variable = x;
    }
    public T getVariable() {
        return variable;
    }

}

class Bar<T> {

    private T foo;

    Bar(T x) {
        foo = (T) new Foo<T>(x);
    }
    public T getFoo() {
        return foo;
    }

}

Foo 中的構造函數需要一個參數; 但你可以這樣做:

public class Bar<T> {

   private Foo<T> foo;

   Bar(T x) {
      foo = new Foo<T>(x);
   }
}

根據您更新的問題,以下內容將起作用:

class Bar<T extends Foo<T>> {  
    private Foo<T> foo;

    Bar() {
        foo = new Foo<T>();
    }
}

請注意,您不應使用原始類型Foo

我不確定我是否理解正確,但你想要這樣的東西嗎?

        public class Bar<T> extends Foo<T> {

           private Foo<T> foo;

           Bar() {
              foo = new Foo<T>();
           }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM