Java Reference
In-Depth Information
. If you want an access intermediate between
and
, then the
protected
public
private
access described in the next paragraph is often a preferable alternative to
.
protected
You may have noticed that if you forget to place one of the modifiers
,
public
before an instance variable or method definition, then your class
definition will still compile. If you do not place any of the modifiers
, or
private
protected
,
,
public
private
or
before an instance variable or method definition, then the instance variable
or method can be accessed by name inside the definition of any class in the same pack-
age, but not outside of the package. This is called
protected
package access
,
default access
, or
friendly access
. You use package access in situations where you have a package of coop-
erating classes that act as a single encapsulated unit. Note that package access is more
restricted than
, and that package access gives more control to the program-
mer defining the classes. If you control the package directory (folder), then you control
who is allowed package access.
The diagram in Display 7.9 may help you to understand who has access to mem-
bers with public, private, protected, and package access. The diagram tells who can
directly access, by name, variables that have public, private, protected, and package
access. The same access rules apply to methods that have public, private, protected,
and package access.
protected
Package Access
If you do not place any of the modifiers
before an instance
variable or method definition, then the instance variable or method is said to have
public
,
private
, or
protected
package
. If an
instance variable or method has package access, it can be accessed by name inside the defi-
nition of any class in the same package, but not outside of the package.
access
. Package access is also known as
default access
and as
friendly access
PITFALL:
Forgetting about the Default Package
When considering package access, do not forget the default package. Recall that all the
classes in your current directory (that do not belong to some other package) belong to an
unnamed package called the
So, if a class in your current directory is not
in any other package, then it is in the default package. So if an instance variable or
method has package access, then that instance variable or method can be accessed by
name in the definition of any other class in the default package.
default package.
Search WWH ::




Custom Search