Why can't I declare and initialize static variable in inner class?

<>

This question already has an answer here:

Answers


You can't have static fields/method in a regular inner classes, because, inner classes will work only with instance of outer classes.

So, static can't be there with instances.

But they can have compile time constants, check JLS 8.1.3. You x, x1, x2 are not compile time constants, while s1, s2, y1, y2 are compile time constants

Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.


You can just make the inner classes static.

static class A {

    static final Object x = new Object();
    static final String s = "s1";
    static final int y = 1;

    static class B {

        static final Object x1 = new Object();
        static final String s1 = "s1";
        static final int y1 = 1;

        static class C {

            static final Object x2 = new Object();
            static final String s2 = "s1";
            static final int y2 = 1;
        }
    }
}

Although obviously this will make some other things difficult.


Need Your Help

How to fix Warning Illegal string offset in PHP

php arrays wordpress casting offset

I have this chunk of PHP code which is giving me the error: