Access Control
Home ] Up ] Qualified Names ] The import Statement ] Automatic Import ] The package Statement ] Compilation Units ] Host Support for Packages ] Type Definitions ] [ Access Control ]

 

 

Access to Package Contents

A package is accessible if the corresponding files and directories are accessible.

All classes (and interfaces) in a package are accessible to all other classes (and interfaces) in the same package.

A class declared public in one package is accessible from within another package. A non-public class is not accessible from outside of its package.

Members of a class are accessible from a different class within the same package, as long as they are not declared private.

private members are accessible only within their own class.

All members of a class are accessible from within that class.

Visibility Modifiers

The keywords public and private (and protected -- later) are visibility modifiers, which have the following effect:

A private member of a class is visible only in methods defined within that class.

A public member of a class is visible to all class methods.

If a member is declared with no visibility modifiers, then it has default package visibility, and is visible only within the class that defines it and within classes defined in the same package. (This is analogous to the friend concept in C++ -- all classes within a package are 'friendly' to each other.)

To summarize:

Accessible to: Member Visibility
public package private
Same class yes yes yes
Class in same Package yes yes no
Subclass in different package yes no no
Non-subclass, different package yes no no

Here are some simple rules to help you choose which visibility modifiers to use, when:

  • Use public only for methods and constants that form part of the public interface (sometimes called the API) of the class.
  • Use the default package visibility for fields and methods that you want to be hidden from outside of the package, but which you want cooperating ('friend') classes within the package to have access to.
  • Use private for fields and methods that are only used inside the class and should be hidden from everywhere else

Note: Try to make all class/instance data private, except for static final fields (i.e. class constants).

 

This page was last modified on 02 October, 2007