Java – multi level static nested classes produce incorrect output

When you run the following code, "x.q" instead of "a" will be printed as required by the language specification

Solution

The reason why you receive "x.q" is that x refers to an unnamed package with X scope, not a < T > 10. Declaring "external" X after B is not important because the java compiler sees B. Y's base class name before it resolves it

You can force inheritance from A. X in your code as follows:

class B extends A<B.Y.Q> {
    static class Y extends A.X {
    } //                   ^^
      //                Add this
}

Demo 1.

Editor: (thanks for user695022's comments)

Strangely, if the external class is not generic, the problem disappears:

class A {
    static class X {
        static class Q {
            public static void main() {
                System.out.println("A<T>.X.Q");
            }
        }
    }
}

Demo 2.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>