2015-05-12 118 views
11

我不明白为什么method2不编译,而method1编译。 我使用的Eclipse与JavaSE的1.7和我的方法2以下错误:为什么<T扩展Enum <T>&SomeInterface>编译,但不是<T扩展SomeInterface&Enum <T>>?

Multiple markers at this line

  • The type Enum<T> is not an interface; it cannot be specified as a bounded parameter

  • Bound mismatch: The type T is not a valid substitute for the bounded parameter <E extends Enum<E>> of the type Enum<E>

public class Test { 

    public interface SomeInterface { 

    } 

    public static <T extends Enum<T> & SomeInterface> T method1() { 
     return null; 
    } 

    public static <T extends SomeInterface & Enum<T>> T method2() { 
     return null; 
    } 
} 

回答

16

如果你看一下在JLS 8.1.2语法的类型参数的边界,你会看到:

TypeBound: 
    extends TypeVariable 
    extends ClassOrInterfaceType {AdditionalBound} 

AdditionalBound: 
    & InterfaceType 

换句话说,只有第一个指定的类型可以是一个类 - 其余的都是接口。

除了别的以外,这可以防止指定多个类。

它也反映了在声明一个类的时候,你必须先把它扩展的类,然后是它实现的接口 - 而不是相反。

+5

按秒殴打。 * Sk​​eet!* \ *摇动拳头* – Radiodef

5

按照docs

A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:

Class A { /* ... */ } 
interface B { /* ... */ } 
interface C { /* ... */ } 

class D <T extends A & B & C> { /* ... */ } 

If bound A is not specified first, you get a compile-time error:

class D <T extends B & A & C> { /* ... */ } // compile-time error 

因为在你的榜样method2有接口SomeInterface第一,它显示了编译器错误

相关问题