Why does <T extends Enum<T> & SomeInterface> compile, but not <T extends SomeInterface & Enum<T>>?

I can't understand why the method2 does not compile whereas method1 does compile. I am using Eclipse with JavaSE 1.7 and I got the following error on method2:

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;
    }
}
Jon Skeet
people
quotationmark

If you look at the syntax for type parameter bounds in JLS 8.1.2 you'll see:

TypeBound:
    extends TypeVariable 
    extends ClassOrInterfaceType {AdditionalBound}

AdditionalBound:
    & InterfaceType

In other words, only the first type specified can be a class - all the rest have to be interfaces.

Aside from anything else, this prevents multiple classes being specified.

It also mirrors the way that when declaring a class, you have to put the class it's extending first, then the interfaces it implements - not the other way round.

people

See more on this question at Stackoverflow