OnJava8-Examples/generics/FactoryConstraint.java

37 lines
638 B
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/FactoryConstraint.java
interface FactoryI<T> {
T create();
}
class Foo2<T> {
private T x;
public <F extends FactoryI<T>> Foo2(F factory) {
x = factory.create();
}
// ...
}
class IntegerFactory implements FactoryI<Integer> {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public Integer create() {
2015-05-05 14:05:39 -07:00
return 0;
2015-04-20 15:36:01 -07:00
}
}
class Widget {
public static class Factory implements FactoryI<Widget> {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public Widget create() {
return new Widget();
}
}
}
public class FactoryConstraint {
public static void main(String[] args) {
2015-05-05 11:20:13 -07:00
new Foo2<>(new IntegerFactory());
new Foo2<>(new Widget.Factory());
2015-04-20 15:36:01 -07:00
}
} ///:~