Dealing With Java Default Level Access Specifiers

Posted by Tom Tresansky on Stack Overflow See other posts from Stack Overflow or by Tom Tresansky
Published on 2010-05-27T15:12:23Z Indexed on 2010/05/27 15:31 UTC
Read the original article Hit count: 238

Filed under:
|
|

I've seen some code in a project recently where some fields in a couple classes have been using the default access modifier without good reason to. It almost looks like a case of "oops, forgot to make these private". Since the classes are used almost exclusively outside of the package they are defined in, the fields are not visible from the calling code, and are treated as private. So the mistake/oversight would not be very noticeable.

However, encapsulation is broken. If I wanted to add a new class to the existing package, I could then mess with internal data in objects using fields with default access.

So, my questions:

  1. Are there any best practices concerning default access specifiers that I should be aware of? Anything that would help prevent this type of accident from re-occurring?
  2. Are are any annotations which might say something to the effect of "I really meant for these to be default access"?
  3. Using CheckStyle, or any other Eclipse plugins, is there any way to flag instances of default fields, or disallow any not accompanied by, say, a "//default access" comment trailing them?

© Stack Overflow or respective owner

Related posts about java

Related posts about java-ee