2

I see that there are two ways to declare/define a variable in JAVA: public and private. My question is what happens if the variables is defined without being treated as "public" or "private", for example:

int num;

Is 'num' considered as private of as public?

user2864740
  • 54,112
  • 10
  • 112
  • 187
user3189985
  • 179
  • 3
  • 13

2 Answers2

6

The are four ways of defining the access permisions of a variable, as described here. If you don't put a keyword before the variable name you are using the default access level modifier.

  • public allows access from anywhere else.
  • protected allows acces from inside the package and the class' subclasses.
  • the default modifier (blank) allows access only from inside the package.
  • private allows access only from inside the class.

Protected and default are quite similar.

robertoia
  • 2,092
  • 20
  • 27
  • Oh sorry, commented the wrong post, meant to comment Salah's post. – Mo H. Apr 13 '14 at 17:51
  • 1
    Related wrt protected/pp: http://stackoverflow.com/questions/5416074/isnt-package-private-member-access-synonymous-with-the-default-no-modifier – user2864740 Apr 13 '14 at 17:52
0

The variable's access in then called package private. That means that it can only be accessed by classes in the same package as the class with the variable.

One use of the package private access modifier is in testing (usually not used for the variables, but for methods and/or constructors)

geoand
  • 49,266
  • 16
  • 140
  • 156