Java inner class visibility puzzle
inner-classes, java
Solution
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.
Problem
Consider the following case: ``` public class A { public A() { b = new B(); } B b; private class B { } } ``` From a warning in Eclipse I quote that: the java complier emulates the constructor A.B() by a synthetic accessor method. I suppose the compiler now goes ahead and creates an extra "under water" constructor for B. I feel this is rather strange: why would class B not be visible as a.k.o. field in A? And: does it mean that class B is no longer private at run time? And: why behaves the protected keyword for class B different? ``` public class A { public A() { b = new B(); } B b; protected class B { } } ```