Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java generics extends Cannot infer arguments

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Every Child is a Parent but not every Parent is a Child.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading