Why can't an inner class use static initializer?

后端 未结 3 1913
陌清茗
陌清茗 2021-01-13 07:19

Quoth JLS #8.1.3:

Inner classes may not declare static initializers (§8.7)......

This is demonstrated as such:<

3条回答
  •  失恋的感觉
    2021-01-13 07:40

    I think it is because the Inner class is itself non static. From Java point of view it is an instance variable and I suppose that(1) the class loader was not designed to crawl into inner non static classes to find and initialize potentiel static objects.

    But it is not in impossibility problem, look at the following example :

    public class Outer {
        public static class Inner {
            Outer owner;
            static String constant;
    
            {
                constant = "foo";
            }
    
            private Inner(Outer owner) {
                if (owner == null) {
                    throw new NullPointerException();
                }
                this.owner = owner;
            }
        }
    
        public Inner newInner() {
            return new Inner(this);
        }
    }
    

    Not even a warning because Inner is declared static.

    But at second sight, it has a pointer to an enclosing Outer instance, can only be created through Outer because it has only a private constructor, and its owner cannot be null. From a programmer point of view, it has all the constraints for a non static inner class and could be used like one (except for special idioms like Outer.this), but from a compiler point of view it is static and it static fields will be correctly be initialized at first Outer class initialization.

    (1) : Pacerier explains in below comment why this is incorrect.

提交回复
热议问题