user3189985
user3189985

Reputation: 189

What happens when a variable is not "public" or "private"?

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?

Upvotes: 2

Views: 5825

Answers (2)

geoand
geoand

Reputation: 63991

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)

Upvotes: 0

robertoia
robertoia

Reputation: 2361

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.

Upvotes: 6

Related Questions