I am relatively new to java and I did some reading about private and public acccess modifiers. I would like to eliminate any confusion once and forall in this topic because I feel like I don’t have the best grasp on it.
Access modifiers in variables
Please correct me if I am wrong, a variable is public on default. If the access modifier is set to public or just not set at all, than other classes from the same project can access the integer and/or modify it. If it is private than it is not visible to the outside and cannot be accessed by classes outside the one in which it was created.
Accesss modifiers in classes
Access modifiers in classes, I don’t seem to fully understand. As far as my understanding, if I call a private method from method that is not in the same class, than it will not work. If it is public than it will?
Is there anything I am missing or don’t understand correctly?
I appreciate help in this regard.
You’re wrong. Assuming you mean fields, by default, they have “package” access, which can’t be expressed explicitly. Local variables have no concept of access control – they only exist within the context of a method anyway, so can’t be referred to from anywhere else.
If it’s set public, then any code can access it.
If it’s default (package) access, then any code in the same package can access it.
That’s pretty much right, yes.
I suggest you read the Java tutorial on all of this, and consult the language spec section 6.6 for more details.