Question

Class Main has a subclass SubMain.

Class Foo has a subclass SubFoo.

In Main:

public List<Foo> getFoo() { return null; }

In SubMain:

@Override
public List<SubFoo> getFoo() { return this.subfoo; }

I get a compiler error though on List<SubFoo>. Am I thinking about this incorrectly? Below are a couple sources that made me think this would work.

http://en.wikipedia.org/wiki/Covariant_return_type

https://stackoverflow.com/a/10134596/1747491

Was it helpful?

Solution

Consider:

public List<? extends Foo> getFoo() { return null; }

As Edwin states, a List<SubFoo> is not a subclass of List<Foo> since you could not add of Foo to a List<SubFoo>.

Other options:

public class Main<T extends Foo>{
   public List<T> getFoo();
}

public class SubMain extends Main<SubFoo>{
  public List<SubFoo> getFoo();
}

or make SubMain return a List<Foo>

OTHER TIPS

List<SubFoo> is not a subtype of List<Foo>, but ArrayList<Foo> is a subtype of List<Foo>.

See Generics link ,

SOLUTION:

You can do something like List<? extends Foo> getFoo()

See Wildcards and Subtypinglink for more

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top