Java inner class visibility puzzle

前端 未结 4 1845
天涯浪人
天涯浪人 2021-01-02 07:03

Consider the following case:

public class A {
  public A() { b = new B(); }
  B b;
  private class B { }
}

From a warning in Eclipse I quot

4条回答
  •  误落风尘
    2021-01-02 07:29

    Inner classes are essentially a hack introduced in Java 1.1. The JVM doesn't actually have any concept of an inner class, and so the compiler has to bodge it. The compiler generates class B "outside" of class A, but in the same package, and then adds synthetic accessors/constructors to it to allow A to get access to it.

    When you give B a protected constructor, A can access that constructor since it's in the same package, without needing a synthetic constructor to be added.

提交回复
热议问题