7.5 Scope of Access | 343
displays a week surrounding a given date. Both of the classes use the Julian day as their in-
ternal representation. It is thus more efficient for aDateobject to make its Julian day mem-
ber directly accessible toShowWeekthan to require conversion of the date first to its external
form and then back to a Julian day in the other object. The user is unaware of this shortcut,
so the encapsulation is preserved.
Classes naturally belong together in a package if they have common internal represen-
tations. In that case, they can bypass each other’s encapsulations because the common de-
tails of their implementations are already known to anyone who’s working with them.
Java defines four levels of access for class members, three of which enable direct access
by other package members. The four levels of access are public,protected, default (package),
and private. There are keywords that we use as access modifiers for each of these levels ex-
cept the package level, which is the default level. If you omit an access modifier from the dec-
laration of a class member, it is at the package level of access by default.
publicAccess A publicmember can be accessed from anywhere outside of the class. User code,
derived classes, and other classes in the same package can all access a publicmember. The
member may still be hidden by a declaration of the same name in another class, in which
case references to it must be qualified with its class or instance name.
Here’s an example of using qualified names. If the classShowWeekdefines ajulianDayfield
andDatealso definesjulianDayas astaticfield, thenShowWeekwould need to refer to
Date.julianDay
to access the static field of Date. If julianDayis an instance field of Dateand the particular ob-
ject is called instanceName, then ShowWeekmust refer to it as follows:
instanceName.julianDay
protectedAccess A protectedmember is accessible to classes in the same
package and can be inherited by derived classes outside of the package.
Code that is outside of the package can only inheritprotectedmembers of a
class; it can’t access them directly.
In the following code segment, we define two packages. The second
package has a class (DerivedClass) that is derived from the class in the first
package (SomeClass).DerivedClassinherits the protectedfield someIntfrom
SomeClass. Notice that DerivedClassdoesn’t include a declaration of someInt.
DerivedClassdefines a method that has one parameter of the class SomeClassand another
parameter of its own class. It then tries to access the someIntfield in both parameters.
packageone;
public classSomeClass
{
protected intsomeInt;
}
Inherit To acquire a field or
method from a superclass