Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics in combination with interface inheritance

I have a problem with generics in Java in combination with interface inheritance. Here is an exampe:

public interface Type0 { }

public interface Type1 extends Type0 {
    void method();
}

public interface SomeInterface0<T extends Type0> {
   T get();
}

public interface SomeInterface1<T extends Type1> extends SomeInterface0<T> { }

Now, when I try to use field of type SomeInterface1 without type parameter java comiler treats type of SomeInterface1.get() method result as Type0. And can't compile something like this:

...
SomeInterface1 si1;
...
si1.get().method();

So, why SomeInterface1<T extends Type1> has a default vlue for T = Type0 ?

like image 300
dbolotin Avatar asked Feb 23 '23 19:02

dbolotin


2 Answers

When leaving out generic parameters, almost all of the generics logic is skipped. Determining the type of T will not be 'smart' and just look at the way T is defined within that class/interface.

If you want to use the generics logic, you should provide generic parameters instead of leaving them out - they can still be very, well, 'generic':

SomeInterface2<? extends Type1> si1;
si1.get().method();
like image 196
Arnout Engelen Avatar answered Feb 28 '23 20:02

Arnout Engelen


Since you're not using a type parameter when declaring the object of type SomeInteface1, the java compiler has no idea what actual class/interface it'll return when you invoke get(). The only thing that's certain is that it's an interface that extends Type0 (given the declaration of SomeInterface0).

When you call get(), the compiler is checking the signature of the interface where get() is declared, so the only methods it knows can be called (without explicit type parameter being given), are the methods declared in Type0.

Let me know if I was too confusing, I'll try to clear up the answer! :P

like image 22
pcalcao Avatar answered Feb 28 '23 21:02

pcalcao