7 Sept 2007

Java generics and interface

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:
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 ;)

Technorati tags:

7 comments:

David said...

Would you explain the difference between using an interface to using generics. when you prefer one over the other?

Benjamin Francisoud said...

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> {}

Anonymous said...

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:)

Unknown said...

Good stuff in java generics and interface..java training in chennai

Chiến SEOCAM said...
This comment has been removed by a blog administrator.
Chiến SEOCAM said...
This comment has been removed by a blog administrator.
Chiến SEOCAM said...
This comment has been removed by a blog administrator.