Given the Java code below, I want to know why upcasting Foo<String>
to Foo<object>
does not work? Essentially I want to tell Java that if T
is a subclass of S
, then Foo<T>
is a subclass of Foo<S>
. I know there is a way to do this in Scala but is there a way to do this in Java? If not, is there a workaround to get the below code to compile?
class Foo<T> {
T t;
public Foo(T t) {
this.t = t;
}
}
class Main {
public static Foo<object> getFoo() {
Foo<String> foo = new Foo("foo");
return foo; // this throws a compile time exception
}
}