Search code examples
javapublicaccess-modifiers

What is the difference between public int and int in Java?


I've only started to learn Java (I'm a student, and C++ is the base langauge I know best) and I've come across access and modifiers.

In code I've seen the use of

 public int NAME;
 // and
 int NAME;

Does it make a difference? If so, what is the difference. What does it do exactly?


Solution

  • Public int is a variable that has no access control. It is effectively a global variable. Unmodified int is a "protected+" int if you will, it operates as a protected int but can't be used by subclasses. Protected ints can be used by subclasses of the class containing that particular int variable. Private ints can only be used within that class. It's generally advisable to use as few public variables as you can in order to promote information hiding/encapsulation to improve security/reliability.

    The Oracle Tutorial page covers it nicely.