How to reproduce java compile/runtime error for generic interface type variables that may not be a subtype of two param interfaces at same time?

99封情书 提交于 2019-12-11 08:59:48

问题


I was reading the Java SE 6 specs and then found some confusing stuff that a I can't reproduce:

A type variable may not at the same time be a subtype of two interface types which are different parameterizations of the same generic interface.

I wrote the following code:

interface Odd {}

interface Even {}

interface Strange extends Odd, Even {}

interface InterfaceOne<O extends Odd, E extends Even> {}

interface InterfaceTwo<O extends Odd, E extends Even> extends Odd, Even {}

public class Test {
    public static void main(String[] args) {
        //Expecting compilation error
        InterfaceOne<Strange, Strange> t1 = new InterfaceOne<Strange, Strange>(){};
        //Expecting compilation error
        InterfaceTwo<Strange, InterfaceTwo> t2 = new InterfaceTwo<Strange, InterfaceTwo>(){};
        System.out.println("" + t1 + t2);
    }
}

The code above is supposed to do not compile, but it does.

How to reproduce the error predicted by specification?


回答1:


From what I understand, the generic type cannot be bound to two or more interfaces where these interfaces extend from another interface that employs a generic argument and the bound interfaces use different type for the generic. I've wrote an example of this:

interface Simple<T> { T aMethod(); }
interface SimpleString extends Simple<String> {}
interface SimpleInteger extends Simple<Integer> {}
public class CompilerError {
    public <T extends SimpleString & SimpleInteger> void here(T interesting) {
        System.out.println(interesting.aMethod());
    }
}

Using javac 1.6.0_32-ea, this brings me the following compiler error

CompilerError.java:5: Simple cannot be inherited with different arguments: <java.lang.String> and <java.lang.Integer>
        public <T extends SimpleString & SimpleInteger> void here(T interesting) {
                ^
1 error


来源:https://stackoverflow.com/questions/32232734/how-to-reproduce-java-compile-runtime-error-for-generic-interface-type-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!