wildcards in generic method of an interface

Discussion in 'Java' started by HK, Jul 14, 2005.

  1. HK

    HK Guest

    Consider the following interface:


    import java.util.List;
    public interface Action<CDTA> {
    void invoke(List<? extends CDTA> r);
    }

    Now I try to implement it like this:

    private static class Xaction implements Action<Number> {
    public void invoke(List<Number> l) {
    // not yet implemented
    }
    }

    The compiler, however, complains that Xaction does not
    implement Action. I can only guess that type-safety
    would break if the implementation was allowed. But how?

    Can someone give an example that goes wrong if the
    above is allowed?

    Harald.
    HK, Jul 14, 2005
    #1
    1. Advertising

  2. On Thu, 14 Jul 2005 01:44:28 -0700, HK wrote:

    > Consider the following interface:
    >
    >
    > import java.util.List;
    > public interface Action<CDTA> {
    > void invoke(List<? extends CDTA> r);
    > }
    >
    > Now I try to implement it like this:
    >
    > private static class Xaction implements Action<Number> {
    > public void invoke(List<Number> l) {
    > // not yet implemented
    > }
    > }
    >
    > The compiler, however, complains that Xaction does not
    > implement Action. I can only guess that type-safety
    > would break if the implementation was allowed. But how?
    >
    > Can someone give an example that goes wrong if the
    > above is allowed?


    Suppose someone calls your invoke method with a List<Double> Perfectly
    fine with the declaration given in your interface. Now, a List<Double> is
    not a List<Number>. A List<Number> can contain nothing but Integers, for
    example. You can add Integers into a List<Number>, but not into a
    List<Double>. Therefore, you must not "downcast" in contents types.

    --
    You can't run away forever,
    But there's nothing wrong with getting a good head start.
    --- Jim Steinman, "Rock and Roll Dreams Come Through"
    Stefan Schulz, Jul 15, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Murat Tasan
    Replies:
    1
    Views:
    8,028
    Chaitanya
    Feb 3, 2009
  2. Benjamin Lerman

    Java 5, Generic, Map and wildcards

    Benjamin Lerman, Mar 9, 2006, in forum: Java
    Replies:
    1
    Views:
    7,665
    Hendrik Maryns
    Mar 9, 2006
  3. Replies:
    2
    Views:
    424
  4. Replies:
    4
    Views:
    338
    timjowers
    Nov 2, 2007
  5. minlearn
    Replies:
    2
    Views:
    445
    red floyd
    Mar 13, 2009
Loading...

Share This Page