Consider the following example:
public class Main {
public static void main(String[] args) {
class Parent {
@Override
public String toString() {
return "this is Parent";
}
}
class Child extends Parent {
}
class C<T extends Parent> {
C(T a) {
System.out.println(a);
}
}
Parent parent = new Parent();
Child child = new Child();
C<Child> c = new C<>(child); // Ok
C<Parent> d = new C<>(parent); // Ok
C<Parent> e = new C<>(child); // Ok
C<Child> f = new C<>(parent); // Compile error - Cannot infer arguments
}
The following statement class C<T extends Parent> implies that class C can be generalized with anything that inherits from parent including both Child and Parent.
So, when I generalize it with Child, and try to call constructor with a Parent instance, why won’t it work?
>Solution :
Every Child is a Parent but not every Parent is a Child.