Radu Dumbrăveanu
Radu Dumbrăveanu

Reputation: 1416

Lower bound elevation in sub classes

I have a hierarchy of classes that can be simplified to the following example

public interface I<T> {
  T get();
}

public interface II<T extends Number> extends I<T> {
}

public class A implements II<Integer> {
  @Override
  public Integer get() {
    return null;
  }
}

public class B implements II<Double> {
  @Override
  public Double get() {
    return null;
  }
}

Now when I'm trying to compile the following code

    II ii = new A();
    Number n = ii.get();

I get a compiler error (at the 2nd line)

java: incompatible types: java.lang.Object cannot be converted to java.lang.Number

I understand that it is because the it takes the lower bound of I which is Object (since method get is declared in I) but I was expecting that it will take the lower bound of II. How can I refactor this hierarchy such that the compiler will consider Number as lower bound. The only restriction is that interface I cannot be modified because it is part of a library.

UPDATE: The idea is that I would like a generic solution

    II ii = <any instance of classes that implements interface II>
    Number n = ii.get();

Upvotes: 0

Views: 52

Answers (2)

IlyaMuravjov
IlyaMuravjov

Reputation: 2502

You shouldn't use raw type II. Replace it with II<?>, and everything will work fine:

II<?> ii = new A();

Upvotes: 0

Sukhpal Singh
Sukhpal Singh

Reputation: 2278

Everything else is ok, declaration need to be changed to II<Integer> ii = new A();, then it works.

For both A and B, you can use II<? extends Number> = new A();

Upvotes: 2

Related Questions