Vincent asked me if it was possible to specify that a generic parameter must implements a specific interface. Well that's possible but instead of writing:
you need to do:
Here's the full code listing:
T implements MyInterface
you need to do:
T extends MyInterface
Here's the full code listing:
public interface Toto {
public void execute();
}
public class TotoImpl implements Toto {
public void execute() {
System.out.println("execute");
}
}
public class Foo <T extends Toto> {
private T t;
public void setObject(T t) {
this.t = t;
}
public T getObject() {
return t;
}
public void doSomething() {
t.execute();
}
}
public class Main {
public static void main(String[] args) {
Toto toto = new TotoImpl();
Foo foo = new Foo();
foo.setObject(toto);
Toto notCastedToto = foo.getObject();
foo.doSomething();
}
}
update: thanks to nico to point that > and lt; wasn't display in the code, making it pointless ;)
7 comments:
Would you explain the difference between using an interface to using generics. when you prefer one over the other?
They don't have the same purpose.
The interface helps to define a hierarchy between object (a 'man' implements a 'person').
class Man implements Person {}
Generics define 'uses' links like: a car can be use by any object of type 'person' (man or woman).
class Car <T extends Person> {}
Nice post! i was struggling with define a type param for an decorator and now i understand it a bit more ..
public class DecoratorBuilder implements Builder
Thanks:)
Good stuff in java generics and interface..java training in chennai
Post a Comment