Generics in Java

二次信任 提交于 2019-12-10 04:06:51

问题


I would like to understand the following type of syntax.

Example:

public interface A < T extends A < T> > {

}

What is the logic of this interface ?


回答1:


This would be used as follows:

class X implements A<X> { /* ... */ }

In other words, you are forced to make the parameter of A the class X itself, and something like class X implements A<Unrelated> is forbidden.

This construction gives the interface access to X through the generic parameter, and the type restriction makes sure that it doesn't get abused. For instance, T can now be assumed to expose all methods that A does.

Note that this construction is formally somewhat similar to the curiously recurring template pattern in C++ (although it is technically quite different). In both languages it allows the "base class" to reason about its ultimate derived usage.



来源:https://stackoverflow.com/questions/8187675/generics-in-java

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