0

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
    }
}
user1413793
  • 9,057
  • 7
  • 30
  • 42

1 Answers1

0

There are two issues,

  1. Foo(T obj) {
  2. Foo<Object> foo....

The below code works fine.

class Foo<T> {
    T obj;
    Foo(T obj) {
        this.obj = obj;
    }
}

class Main {
    public static Foo<Object> getFoo() {
        Foo<Object> foo = new Foo("foo");
        return foo;
    }
}
Faraj Farook
  • 14,385
  • 16
  • 71
  • 97