R
Robert Elliot
I'm trying to compile the following code:
public class Foo {
public List<Object> foo() {
return new ArrayList<Object>();
}
}
public class FooExt extends Foo {
public List<String> foo() {
return (List<String>) super.foo();
}
}
The compiler doesn't like it at all; it objects both:
1) to the cast from List<Object> to List<String>, and
2) to over-riding Foo.foo()'s List<Object> return type with
List<String>.
I don't really understand what the problem is; Java 1.5 supports
covariant return types, so
public String foo()
can over-ride
public Object foo()
- what's the difference when over-riding the generic return type?
Equally, Java will happily let me try to do a cast (String) Object;
it'll fall over at runtime if the thing isn't a String. So why can't
I do a cast (List<String>) List<Object> and have it fall over at
runtime if the List contains things that aren't Strings?
Cheers for any help,
Rob
public class Foo {
public List<Object> foo() {
return new ArrayList<Object>();
}
}
public class FooExt extends Foo {
public List<String> foo() {
return (List<String>) super.foo();
}
}
The compiler doesn't like it at all; it objects both:
1) to the cast from List<Object> to List<String>, and
2) to over-riding Foo.foo()'s List<Object> return type with
List<String>.
I don't really understand what the problem is; Java 1.5 supports
covariant return types, so
public String foo()
can over-ride
public Object foo()
- what's the difference when over-riding the generic return type?
Equally, Java will happily let me try to do a cast (String) Object;
it'll fall over at runtime if the thing isn't a String. So why can't
I do a cast (List<String>) List<Object> and have it fall over at
runtime if the List contains things that aren't Strings?
Cheers for any help,
Rob