Skip to content

March 3, 2011

Java member access levels – public, protected, private

Java access level cheat sheet:

Chart shows java access levels

 *no modifier is usually refered to as package-private.

  • Classes can be declared:
    • public
    • package-private
  • Methods and member variables can be declared: 
    • public
    • protected
    • package-private
    • private

It’s easy to remember the effect of public and private.  One grants total access, while the other restricts access to the class itself.  Both protected and package-private grant access to the package, but only protected grants access to subclasses.

Good practice dictates that you keep access as restricted as possible.  This enforces encapsulation and helps forestall bugs in the code.  Keep in mind, both public and protected members become part of your API forever (unless you want to break clients, which is not nice).  Preserving encapsulation ensures you are not tied to a particular implementation and keeps your API clean. 

More Here.

If you repost the chart above, please cite this blog.  (icons from famfamfam)

Read more from Java

Share your thoughts, post a comment.


Note: HTML is allowed. Your email address will never be published.

Subscribe to comments