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

泪湿孤枕 提交于 2020-01-04 01:55:28

问题


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?


回答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.



来源:https://stackoverflow.com/questions/37906896/is-there-a-need-to-declare-access-modifiers-in-a-private-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!