Reputation: 10425
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
Upvotes: 0
Views: 47
Reputation: 32969
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>
Upvotes: 5
Reputation: 11487
List<SubFoo>
is not a subtype of List<Foo>
, but ArrayList<Foo>
is a subtype of List<Foo>
.
See Generics
link ,
You can do something like List<? extends Foo> getFoo()
See Wildcards and Subtyping
link for more
Upvotes: 1