Normally when creating new global variables I do not define its access modifier. So as per java it will adopt property default access modifier. When I'm need to access that variable in out of default scope I change its access modifier else leave it as it is. So my question is "Am I doing it right way? Is it normal to have default access variables? or should I use private/public for them? Is it good coding practice to not to use access modifiers?"
2 things here:
- don't use globals :)
- it's common/best practice to assume all fields are private unless there's an overriding reason to make them anything else, in which case the most restrictive access should be chosen (usually protected).
Of course there's always exceptions to the rule, but that's the basics to start out from.
A few general programming principles here:
- Simple is better
- Don't state the obvious
- Explicit is better than implicit
I'm not a Java expert, but the general rule of thumb should be: If what happens is obvious to someone familiar with the language without being explicit, use the implicit behavior. If however this might put someone on the wrong track, then by all means be explicit.
Java doesn't have automatic properties, so all class member(s) in general should be private with get/set methods for public usage, if required.
According to the source (Oracle java Docs) this is the recommended approach.
"Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to. Avoid public fields except for constants. Public fields tend to link you to a particular implementation and limit your flexibility in changing your code. "