7 Sep 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() {

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() {

public class Main {
public static void main(String[] args) {
Toto toto = new TotoImpl();
Foo foo = new Foo();
Toto notCastedToto = foo.getObject();

update: thanks to nico to point that > and lt; wasn't display in the code, making it pointless ;)

Technorati tags:


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


Geetha Devi said...

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

Pavithra M said...

It is really a great work and the way in which u r sharing the knowledge is excellent.
Thanks for helping me to understand basic concepts. As a beginner in java programming your post help me a lot.Thanks for your informative article.java training in chennai | chennai's no.1 java training in chennai