2015-04-20 15:36:01 -07:00
|
|
|
|
//: generics/SelfBounding.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
|
|
|
|
|
class SelfBounded<T extends SelfBounded<T>> {
|
|
|
|
|
T element;
|
|
|
|
|
SelfBounded<T> set(T arg) {
|
|
|
|
|
element = arg;
|
|
|
|
|
return this;
|
|
|
|
|
}
|
|
|
|
|
T get() { return element; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class A extends SelfBounded<A> {}
|
|
|
|
|
class B extends SelfBounded<A> {} // Also OK
|
|
|
|
|
|
|
|
|
|
class C extends SelfBounded<C> {
|
|
|
|
|
C setAndGet(C arg) { set(arg); return get(); }
|
2015-05-18 23:05:20 -07:00
|
|
|
|
}
|
2015-04-20 15:36:01 -07:00
|
|
|
|
|
|
|
|
|
class D {}
|
|
|
|
|
// Can't do this:
|
|
|
|
|
// class E extends SelfBounded<D> {}
|
|
|
|
|
// Compile error: Type parameter D is not within its bound
|
|
|
|
|
|
2015-04-29 12:53:35 -07:00
|
|
|
|
// Alas, you can do this, so you cannot force the idiom:
|
2015-04-20 15:36:01 -07:00
|
|
|
|
class F extends SelfBounded {}
|
|
|
|
|
|
|
|
|
|
public class SelfBounding {
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
A a = new A();
|
|
|
|
|
a.set(new A());
|
|
|
|
|
a = a.set(new A()).get();
|
|
|
|
|
a = a.get();
|
|
|
|
|
C c = new C();
|
|
|
|
|
c = c.setAndGet(new C());
|
|
|
|
|
}
|
2015-05-05 11:20:13 -07:00
|
|
|
|
} ///:~
|