Java泛型类,如何创建实例

3

I have the following class structure:

public abstract class Generic<T extends SuperClass>

public class SuperGeneric<T extends SuperClass & SomeInterface> 
    extends Generic<T>

现在我想创建一个覆盖所有可能类的SuperGeneric实例。我尝试了以下方法:
Generic<? extends SuperClass & SomeInterface> myGeneric 
    = new SuperGeneric<? extends SuperClass & SomeInterface>();

现在似乎无法正常工作。 在“Generic”上它给出了以下错误:Incorrect number of arguments for type Generic<T>; it cannot be parameterized with arguments <? extends SuperClass, SomeInterface>
而在“new SuperGeneric”中,我得到了类似的错误:Incorrect number of arguments for type SuperGeneric<T>; it cannot be parameterized with arguments <? extends SuperClass, SomeInterface>
你知道如何正确创建这个“SuperGeneric”的实例吗?
我的想法是有2个不同的类符合“extends SuperClass & SomeInterface”条件,但这些不能被一个类型泛化。
2个回答

2

当你想实例化一个泛型类时,你需要提供具体的类型。你说有两个类满足限制条件,假设它们是 Type1Type2

然后你应该可以这样做:

Generic<Type1> myGeneric1 = new SuperGeneric<Type1>();

并且

Generic<Type2> myGeneric2 = new SuperGeneric<Type2>();

通配符仅用于声明。它们的含义是:您可以在此处放置任何类型(满足给定约束条件的类型)。

那么通配符在哪里使用呢?在方法参数和返回类型中吗? - Steven Roose
@stevenroose 请看我的最后一句话。 - hage

2
当您实例化时,需要提供一个类型供编译器填充。

那么通配符在哪里使用呢?在方法参数和返回类型中吗? - Steven Roose
通配符描述了T可以是什么,但你实际上需要为T提供一些内容。 - nsfyn55
你正在混淆类字面量和其他泛型特性。 - nsfyn55
http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html - 这是Oracle的教程。 - nsfyn55
我也觉得Java的语法很令人困惑。在C#中,您将类型约束放在单独的子句中(使用where关键字);而在Java中,您将类型约束声明放在泛型声明内部(Generic<T extends ClassNameHere>),因此您对如何实例化它感到困惑。话虽如此,当您进行实例化(无论是Java还是C#)时,它们都非常简单,使用相同的语法(即Generic<SomeClass> x = new SuperGeneric<SomeClass>())。请参考我在http://www.anicehumble.com/2012/05/c-said-java-said-constraining-generics.html上的比较。 - Michael Buen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接