7.5 Scope of Access | 345
{
voiddemoMethod(SomeClass param1, DerivedClass param2)
{
param1.someInt = 1;
param2.someInt = 1;
}
}
privateAccess Lastly, the privatemodifier cuts off all external access, even by classes in the
same package. A privatemember of a class can be referred to only by other members of the
class, and only the internal scope rules apply to it. It isn’t even permissible for a derived
class in the same package to access a privatemember of its superclass.
Instances of a class can refer to each other’s privatemembers. A member is privateto
its class, which includes all instances of the class. Thus two objects,someObjand otherObj, that
have private intfields called someIntcan refer to each other’s fields. That is,someObjcan re-
fer to otherObj.someIntand otherObjcan refer to someObj.someInt.
Within a method, all local identifiers are automatically private; Java doesn’t allow us to
declare them with access modifiers. The reason is that the lifetime of a local identifier is lim-
ited to a particular method call, so it simply doesn’t exist when external code is running. Table
7.1 summarizes the external scope rules.
So far, we have primarily used the publicand package levels of access, keeping data
members at the package level and making most methods and classes public. This simple
scheme provides encapsulation and a consistent user interface that is strictly a set of method
calls. However, this scheme is inflexible and limits our ability to provide for either extension
or the construction of related classes that are grouped into a package.
Now that we have a better understanding of Java’s access rules, we must consider which
access modifier is most appropriate for each member of a class. Once you have identified all
of its members, take a second look at each one and ask the following question:
Do I want to access this member from other classes in the same package, from derived classes, or
from user code?
Based on your answer to each part of this question, use Table 7.1 to decide which access
modifier is most appropriate.
External Access public protected Default (package) private
Same package yes yes yes no
Derived class in another yes yes no no
package (inheritance only)
User code yes no no no
Table 7.1 Java’s External Scope Rules