泛型自限定
class SelfBounded<T extends SelfBounded<T>>{ T element; SelfBounded<T> set(T arg){ element = arg; return this; } T get() { return element; } }
class D{} class A extends SelfBounded<A>{} // class E extends SelfBounded<D>{} 会报错
格式: class SelfBounded<T extends SelfBounded<T>>
自限定会强制要求正在定义的类当做参数传递给基类.看格式就能看出来.
2.参数协变
interface SelfBoundSetter<T extends SelfBoundSetter<T>>{ void set(T arg); } interface Setter extends SelfBoundSetter<Setter>{ } public class SelfBoundingAndCovarianArguments { void testA(Setter s1 , Setter s2 ,SelfBoundSetter sbs) { s1.set(s1); s1.set(s2); // s1.set(sbs); 编译错误 } }
通过泛型自限定可以可以限制参数使用定义的类.