I thought I understood the concept of generics, until today I found this problem: I am using Java 11. I know, that the design of the following code does not really make sense, it is only intended to reproduce the problem that I found in my actual project.
Imagine, I have the following classes:
public class Pet {}
public class Cat extends Pet {
private String catName;
// ... Constructor, Getter, Setter;
}
public class Dog extends Pet {
private String dogName;
// ... Constructor, Getter, Setter;
}
public interface PetExchanger<IN_TYPE extends Pet, OUT_TYPE extends Pet> {
OUT_TYPE exchange(IN_TYPE pet);
}
public class PetExchangings<S extends Pet> {
public <IN_TYPE extends Pet, OUT_TYPE extends Pet> void exchangingRule(Class<IN_TYPE> inClass Class<OUT_TYPE> outClass,
PetExchanger<IN_TYPE, OUT_TYPE> f) {
// no matter what happens here ...
}
}
public class Main {
public static void main(String[] args) {
new PetExchangings().exchangingRule(Dog.class, Cat.class, d -> new Cat(d.getDogName()));
}
}
This code does NOT compile, unless I remove the generics definition <S extends Pet>
on the class PetExchangings
. If I remove it, everything is fine, but with this definition added (which does not seem to influence anything!) suddenly the call of exchangingRule(...)
from the main
method does not compile any more: The type of the argument "d
" in the lambda expression is suddenly not evalutated as Dog
any more but is only a Pet
. And thus the method d.getDogName()
can not be found.
Can someone please explain to me, why does this happen? How does the generics argument added to the PetExchangings
class influence this behavior? It seems to be in no way bound to the executed method.
` you should add a type on initialization: `new PetExchangings()`. But in this context, it does not make sense to add the generic type to the `PetExchangings` because it is never used. – Titulum Jan 23 '20 at 07:20