Java Coding Style – Should Default Access Modifier Be Used?

access-modifierscoding-stylejava

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?"

Best Answer

2 things here:

  1. don't use globals :)
  2. 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.