Is there a difference in terms of access to the fields a and b ?

 // X.java package XY; class X { int a; }; // Y.java package XY; class Y { public int b; }; 

2 answers 2

The public access public for the class / method / field, etc. - you can apply anywhere. If you do not specify it, then it will be possible to access it only from the class where it is declared and from the entire package .

If a class without a modifier, then the modifiers of its components (methods, fields, etc.) go into the background. The first is the class itself. That is, if the public field is in a class without a modifier, then it cannot be accessed from a subclass or from another package

  • Did not quite understand the question. - Flippy
  • If you do not write a modifier, then the variable will be available in the class where it is declared and in the whole package . - Flippy
  • So with all methods, constants, etc. - Flippy
  • Huh, you confused me) - Flippy
  • In my case, class X has a default access modifier, and its field is a public? - monkey

There are several access levels:

  1. default - used when no access modifier is specified. In this case, the variable is available to the class itself where it is listed, to its internal classes and all classes in the same package with it.
  2. private - available only to the class itself and its internal classes.
  3. protected - available to the class itself, its internal classes and its heirs
  4. public - accessible to everyone and everywhere
  • I'm interested in 4 points, if the class is specified without a modifier, then it is default, right? And if it has a public field, then it cannot be accessible everywhere, because the default class itself? - monkey
  • Read my answer carefully - Flippy
  • Sorry, about default - inner classes cannot be accessed - Flippy
  • @ SergeyGrushin, just checked - the inner classes have absolutely full access to the outer class. Even to private fields - YurySPb
  • docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html there is a table and it says that if the class is default, then they do not have access to them. - Flippy