Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the private keyword in a class level field declaration actually do anything?

Tags:

java

I'm refactoring a bunch of classes, written by different people, which do not have consistent standards. During the course of this, I came to ponder on whether there is any difference between these declarations:

public class foo(){

    int fooBar = 1;

    ......

and

public class foo(){

    private int fooBar = 1;

    ......

Please note that this is a question of semantics, I am fully aware of scoping, encapsulation etc. The question is, does using the private scope annotation in a class field do anything?

Thanks for all thoughts..

(PS. My current level of understanding says there is no difference)

like image 798
Simon Avatar asked Jan 18 '26 03:01

Simon


1 Answers

Absolutely there is a difference. The default access level for a class member in Java is package-private, not private. This means that in the first version any class in the same package as Foo can access fooBar, while in the second version this is not the case.

like image 175
Adam Mihalcin Avatar answered Jan 19 '26 19:01

Adam Mihalcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!