3

Let's say I have a class like this:

public class OuterClass {
  //...
  private class InnerClass {
     private int x; // This variable makes sense
     public int y; // Is there any use for this?
  }
}

In the code above, since the inner class is private, only the outer class has access to all its variables, even the private ones. The inner class itself is not visible to any other class but the enclosing outer class.

So even though variable y above is public, it cannot be accessed by any other class other than the outer class.

It would seem all access modifiers in the private inner class are by default private, aren't they?

So given that, is there any reason to declare access modifiers at all for any of the members of the inner class?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kingamere
  • 9,496
  • 23
  • 71
  • 110
  • 1
    `public class InnerClass2 extends InnerClass {}` (though I wouldn't recommend this) – fabian Jun 19 '16 at 12:00
  • @fabian and what does that do? InnerClass2 would still be able to access all of `InnerClass`'s public and private fields. – Kingamere Jun 19 '16 at 12:01
  • 1
    This way you could create an instance of the `public` subclass of `InnerClass` which would provide access to the `public` members of it's superclass. Cannot think of a real use case though... – fabian Jun 19 '16 at 12:03
  • @fabian ahh didn't think of that, thanks – Kingamere Jun 19 '16 at 12:05
  • 2
    Related - almost dup http://stackoverflow.com/questions/6264657/why-make-private-inner-class-member-public-in-java – leonbloy Jun 19 '16 at 13:18
  • Not sure how I didn't see that question first – Kingamere Jun 19 '16 at 13:19

1 Answers1

1

Case where the access modifier may matter are for methods that override a superclass method(e.g. toString()). You can not reduce the visibility of an overridden method. toString() must always be declared public in order for the class to compile.

When private members are accessed by the outer class, the compiler creates a synthetic method. This synthetic method is only visible in the .class file of the nested class.

Another case when access modifier scope matters when the inner class itself is not private.