Tuesday, April 22, 2008

Advices about using access modifiers in Java

  • Public: For those methods that are necessary to use an object. Note that attributes should never be public. If other objects need access to attributes, create getters and declare them as final.
  • Protected: Best reserved specifically for subclass use. I do not declare anything as protected unless I know that a subclass absolutely needs it. In general, I do not declare methods and attributes as protected in the chance that a subclass may need it sometime in the future. If my design does not justify it explicitly, I declare everything that is not in the public interface as private.
  • Private: For all methods not in the public interface and not designed for use by subclasses.
  • Package Protected: Like protected this level is best reserved specifically for subclass use. However, package protected acts more restrictive than protected. A subclass appearing outside of the class's package will not be able to access package protected features. Package protected is useful if you want to open features to your subclasses but want to restrict access to those who might not understand the full design or consequences of using a feature.

0 comments: