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:

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

    ReplyDelete
  2. 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> {}

    ReplyDelete
  3. Anonymous10:59 am

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

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

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
  7. This comment has been removed by a blog administrator.

    ReplyDelete

Note: only a member of this blog may post a comment.