Joker
Joker

Reputation: 11146

Compilation fails on using Generics?

I wrote the following code which works absolutely fine. The problem is when I change the class from A to Generics A<T> then it fails to compile.

public class A {
    class B {
    }

    static void m(B i) {
    }

    static class C extends B {
        C() {
            new A().super();
        }

    }
}

When i change A to A<T> compilation fails with following error on B.

Cannot make a static reference to the non-static type B

public class A<T> {
    class B {
    }

    static void m(B i) {
    }

    static class C extends B {
        C() {
            new A().super();
        }
    }
}

Why is it working fine in the first case and failing in the second?

Upvotes: 2

Views: 61

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

In the generic case, when you refer to B, you are really referring to an instance of A<T>.B.

Unless you have an enclosing instance of A<T>, you are effectively trying to enclose a raw reference to an A. That's not allowed, because B wants to refer to the type variable associated with its enclosing instance, which doesn't exist.

In the non-generic case, there's no type variable, so B isn't trying to refer to something which doesn't exist.

The simplest solution is to add the A<T> explicitly, e.g.

static void m(A<?>.B obj)

or

static <T> void m(A<T>.B obj)

and

static class C<T> extends A<T>.B {
    C() {
        new A<T>().super();
    }
}

Upvotes: 6

Related Questions