2

If your class in Java is declared private, is possible to have public variables in the code? Would other classes be able to access it?

Timothy Tran
  • 91
  • 3
  • 9
  • 6
    Have you considered simply trying it out? It's not that much effort to code 3 classes and watch the effects. –  Feb 09 '17 at 02:21
  • Probably related: http://stackoverflow.com/questions/6264657/why-make-private-inner-class-member-public-in-java, however you shouldn't be having public variables but public methods to access them (i.e. `getters` & `setters`) – Frakcool Feb 09 '17 at 02:23
  • Yes it is possible. Whether it is helpful / useful / applicable depends on what you are trying to do. (Hint: top-level classes **cannot** be `private`!!) – Stephen C Feb 09 '17 at 02:23
  • It is possible if you are asking whether the compiler will respect it. But what problem are you addressing by such design? – Siddharth Tyagi Feb 09 '17 at 02:25
  • Sometimes I'll make members less restricted than their class as a way of conveying which members are meant to be accessed externally. Also, if a private class were extracted at some point, it requires less refactoring if members have the appropriate visibility. But it's more common with methods, as they may be overriding/implementing a method with greater visibility. – shmosel Feb 09 '17 at 02:30
  • 1
    Not a great duplicate. The question is the same, but the answers are very weak. – shmosel Feb 09 '17 at 02:41

1 Answers1

6

Yes, it is possible to specify public access modifier for a field in java irrespective of the access modifier of its container class.

By definition public access modifier has the biggest scope. So as long as you can access your private class you will be able to access public fields within it. Which in this case will be within the scope of your private class' parent.

Siddharth Tyagi
  • 395
  • 2
  • 8