[英]How do I inherit from a generic class in java?
我有一個像下面這樣的課程
public class Foo<idType extends WritableComparable<idType>, EData extends Writable> {
public Foo();
public Foo(idType foo; idType bar){
this.foo = foo;
this.bar = bar;
}
private idType foo;
private idType bar;
}
現在,這個類的一個用法如下:
elist = new ArrayList<Foo<StringType, EmptyType>>();
所以這很好用:
現在我想擴展這個類以添加一個字段
私人String foobar;
現在,基本上這個實例將有三個字段。
他們兩個人
foobar.foo //base class
foobar.bar //base class
foobar.foobar // new variable added
現在,我的用法仍然是相同的:
elist = new ArrayList<FooBar<StringType, EmptyType>>();
我嘗試了一個簡單的擴展:
public class Foobar extends Foo{
private String foobar;
public FooBar(String foobar){this.foobar = foobar;}
}
但是當我使用時
我收到一個錯誤:
elist = new ArrayList<FooBar<StringType, EmptyType>>();
ArrayList<FooBar><StringType,EmptyType>> cannot be resolved to a type
如果要讓用戶指定子類的類型,請指定相同的類型參數,並將它們傳遞給基類:
public class FooBar <idType extends WritableComparable<idType>, EData extends Writable>
extends Foo<idType, EData>
{
...
}
如果你想讓用戶只指定其中一種類型,你可以這樣做,例如你想為idType
強制Integer
:
public class FooBar <EData extends Writable>
extends Foo<Integer, EData>
{
...
}
如果你只想使用特定類型的基礎,同樣的想法:
public class FooBar
extends Foo<Integer, Something>
{
...
}
你甚至可以添加一個類型:
public class FooBar <idType extends WritableComparable<idType>, EData extends Writable, AnotherType>
extends Foo<idType, EData>
{
private AnotherType x;
...
}
關鍵是,您可以以任何您認為合適的方式在子類中指定自己的參數類型,只要它們是兼容類型,您就可以將這些類型傳遞給基類。
編輯:響應上面問題的注釋,您必須在FooBar
類型參數上指定與基本Foo
上的約束匹配的約束。 例如,以下內容是不夠的:
public class FooBar <idType, EData>
extends Foo<idType, EData> // <-- will fail to compile
{
...
}
這將導致以下編譯錯誤:
type parameter idType is not within its bound
type parameter EData is not within its bound
這是因為Foo
期望分別擴展WritableComparable<idType>
和Writable
類型,但上面錯誤的FooBar
聲明嘗試將不滿足這些約束的類型作為類型參數傳遞給Foo
。
順便說一句,您發布的錯誤似乎與您的代碼不符,並且最后還有一個額外的>
。 看來你在復制和粘貼時寫了一個拼寫錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.