如何从java中的泛型类继承?
我有一个像下面这样的班如何从java中的泛型类继承?,java,generics,subclass,Java,Generics,Subclass,我有一个像下面这样的班 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;
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<FooBar<StringType, EmptyType>>();
}
但是当我使用
我得到一个错误:
elist = new ArrayList<FooBar<StringType, EmptyType>>();
ArrayList<FooBar><StringType,EmptyType>> cannot be resolved to a type
elist=newarraylist();
ArrayList>无法解析为类型
如果您想让用户为您的子类指定类型,请指定相同的类型参数,并将它们传递给基:
public class FooBar <idType extends WritableComparable<idType>, EData extends Writable>
extends Foo<idType, EData>
{
...
}
如果您只想对基础使用特定类型,同样的想法是:
public class FooBar
extends Foo<Integer, Something>
{
...
}
这将导致以下编译错误:
type parameter idType is not within its bound
type parameter EData is not within its bound
这是因为Foo
需要分别扩展WritableComparable
和Writable
的类型,但是FooBar
的上述错误声明试图将不满足这些约束的类型作为类型参数传递给Foo
顺便说一下,您的错误与您的代码不匹配,并且在末尾有一个额外的
。似乎您在复制和粘贴时输入了错误。应该是公共类Foobar extensed Foo
@GiulioFranco您必须在Foobar
类型参数上指定匹配约束,否则您将得到“类型参数不在其范围内”编译过程中,试图将这些类型传递到基Foo
@JasonC时出错是的,我知道,我在阅读问题时很粗心。无论如何,你已经提供了一个更完整的答案,所以我认为这甚至不值得编辑我的评论。
public class FooBar <idType extends WritableComparable<idType>, EData extends Writable>
extends Foo<idType, EData>
{
...
}
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;
...
}
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