Generics in subclassing

From: Carsten Langer (carsten.langer_at_nokia.com)
Date: 07/29/04


Date: Thu, 29 Jul 2004 19:54:41 GMT

Hi,

I try to get my head around generics, but fail at a specific point. Any help
is appreciated.

Imagine those 2 classes:

 class Composite<T> implements java.lang.Iterable<T> {
     public Iterator<T> iterator() {
         return null; // todo implement
     }
 }

 class Foo extends Composite<Foo> {
     Iterator<Foo> i = iterator();
 }

This works fine. However, what I really want is that Composite guarantees
that iterator() returns back at least a Composite, i.e. a Composite or a
subtype of it. I want to prevent situations like that

    class OtherFoo extends Composite<Bar> {
    }

where OtherFoo.iterator() would return an Iterator<Bar> and Bar is not
subtype of Composite.

But how to do this? If I change Composite to

 class Composite<T extends Composite> implements java.lang.Iterable<T> {
 ...}

thus indicating that T shall be a Composite or subtype of it, then I get a
compile error on the first line in class Foo at the point of the parameter
type <Foo>:

class Foo extends Composite<Foo *compiler error here*> { ...

Error:
Bound mismatch: The type Foo is not a valid substitute for the bounded
parameter <T extends Composite> of the type Composite<T>.

Any idea?
Thanks
Carsten



Relevant Pages

  • Re: Generics in subclassing
    ... > that iteratorreturns back at least a Composite, ... > subtype of Composite. ... > compile error on the first line in class Foo at the point of the parameter ... public Iterator<T> iterator{ ...
    (comp.lang.java.programmer)
  • Re: Generics in subclassing
    ... thank you for confirming that the code as such is correct. ... eclipse3.0/cheetah06 and got the compile error. ... what I really want is that Composite ... >> subtype of Composite. ...
    (comp.lang.java.programmer)