I have and interface:

import java.util.Optional;

public interface SomeInterface<T> {
    Optional<Integer> someMethod();
}

Let us call a method of the interface instance:

public class CheckInterfaceInstance {
    public void check(SomeInterface<?> instance) {
        instance.someMethod().get().doubleValue();
    }
}

All is good, no compilation errors.

But if I declare the argument of the check() method without "any type" then we have a compilation error:

public class CheckInterfaceInstance {
    public void check(SomeInterface instance) {   //I removed <?>
        instance.someMethod().get().doubleValue();
    }
}

Compiler treats the type of instance.someMethod().get() as Object. So it complains about not existing method .doubleValue().

As you can see Optional<Integer> someMethod() declaration is not related to the <T> of SomeInterface at all. But the compiler misses the type of Optional.

Why?

0 Answers