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?"
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
2 things here:
Of course there's always exceptions to the rule, but that's the basics to start out from.
A few general programming principles here:
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. "