2012-09-18 82 views
1

我有下面的类层次结构。绑定不匹配泛型

一流

class First<T> { 
} 

二等

class Second<T> extends First<T> { 

} 

三等

class Third<T extends First<T>> { 
} 

错误行:

Third<Second<String>> name = new Third<Second<String>>();//Compilation error 

Bound mismatch: The type Second<String> is not a valid substitute for the bounded parameter <T extends First<T>> of the type Third<T>

我与上述错误真的很困惑。你能解释为什么这个编译错误发生?

回答

2

T extends First<T>Second<String>不一样,因为T与String以及延伸First<T>的东西都是绑定的。

我必须要在三到使用不同的参数的感觉,在你的作业做这样

class Third<T extends First<?>> { 
} 
+0

你也可以做'第三个>' –

+0

'第三个> {}'给出编译错误。 –

0

东西的困惑是,在TSecondStringTThirdSecond<String>。因此,为了使作业有效,Second<String>应延伸至First<Second<String>>。但情况并非如此,因为Second<String>延伸First<String>。下面的代码编译为预期:

public class Test { 

    static class First<T> { 
    } 

    static class Second<T> extends First<Second<T>> { 
    } 

    static class Third<T extends First<T>> { 
    } 

    public static void main(String... args) { 
     Third<Second<String>> name = new Third<Second<String>>(); 
    } 
} 
1

奥古斯托是在正确的轨道上,但要避免使用通配符?你可以另一种类型的参数添加到您的类Third

class Third<U, T extends First<U>> { 
    // ... 
} 

Third<String, Second<String>> name = new Third<>(); 

的缺点是,您必须在类型参数中提及String两次。