Monday, July 5, 2010

Access Specifiers

How a member can be accessed is determined by the access specifier that modifies its declaration. Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved.

• When a member of a class is modified by the public specifier, then that member can be accessed by any other code.

• When a member of a class is specified as private, then that member can only be accessed by other members of its class.

• When a member of a class is specified as protected, then that member of a class is public within its own package and in subclasses in other packages, but cannot be accessed by non-subclasses outside its package.
• When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.

Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member does not have an explicit access specification the default access is used, it is visible to subclasses as well as to other classes in the same package. If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.


PrivateDefaultProtectedPublic
Same classYesYesYesYes
Same package subclassNoYesYesYes
Same package non-subclassNoYesYesYes
Different package subclassNoNoYesYes
Different package non-subclassNoNoNoYes

No comments:

Post a Comment