Kingamere
Kingamere

Reputation: 10122

Is there a need to declare access modifiers in a private inner class

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?

Upvotes: 4

Views: 1071

Answers (1)

Dungeon_master
Dungeon_master

Reputation: 69

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.

Upvotes: 1

Related Questions