-5

We cannot instantiate an inner class within a static context of the outer class, but when we declare this inner class as package- private. we are able to access its constructor. But how ? what is the magic of the constructors ? Are they bounded to the objects or classes ?

8
  • 8
    Please show a code example of what you mean. Commented Nov 14 at 20:04
  • 4
    "Are they bounded to the objects or classes ?" - Inner classes (i.e. non-static, nested classes) are bound to instances of the outer class. static nested classes are not bound to an instance of the object. See the official java tutorial at docs.oracle.com. Commented Nov 14 at 20:24
  • 4
    Changing the access level of a nested (or any) class's constructor does not affect whether that class can be instantiated from a static context. Commented Nov 14 at 21:33
  • 6
    To allow this question to be answered please edit it and add a minimal reproducible example, please. Commented Nov 14 at 21:40
  • 2
    The 'magic' you are most likely missing is that the Inner in: class Outer { class Inner {}} secretly adds to all the constructors of Inner a parameter Outer this$outer, which javac fills in for you if any this exists to do that with. If you don't understand any of this, that's.. common and this is rather advanced and confusing java. The solution to just opt out of all this confusion and complexity is very simple: Always declare ALL your inner classes as static no matter what. Or, of course, learn the trickiness of java's inner classes mechanics. Commented Nov 15 at 17:36

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.