Posted on Leave a comment

Members with Package Access – Access Control

Members with Package Access

No access modifier implies package accessibility in this context. When no member access modifier is specified, the member is accessible only by other classes in the same package in which its class is declared. Even if its class is accessible in another package, the member is not accessible elsewhere. Package member access is more restrictive than protected member access.

In Example 6.8, the instance field pkgBool in an instance of the class Superclass1 has package access and is only accessible within pkg1, but not in any other packages— that is to say, it is accessible only by Client 1 and Client 2. Client 3 and Client 4 in pkg2 cannot access this field.

private Members

The private modifier is the most restrictive of all the access modifiers. Private members are not accessible by any other classes. This also applies to subclasses, whether they are in the same package or not. Since they are not accessible by their simple names in a subclass, they are also not inherited by the subclass. A standard design strategy for a class is to make all instance fields private and provide public get methods for such fields. Auxiliary methods are often declared as private, as they do not concern any client.

None of the clients in Figure 6.5 can access the private instance field privLong in an instance of the class Superclass1. This instance field is only accessible in the defining class—that is, in the class Superclass1.

Table 6.3 provides a summary of access modifiers for members in a class. References in parentheses refer to clients in Figure 6.5.

  

Table 6.3 Accessibility of Members in a Class (Non-Modular)

Member accessIn the defining class Superclass1In a subclass in the same package (Client 1)In a non-subclass in the same package (Client 2)In a subclass in a different package (Client 3)In a non-subclass in a different package (Client 4)
publicYesYesYesYesYes
protectedYesYesYesYesNo
packageYesYesYesNoNo
privateYesNoNoNoNo
Additional Remarks on Accessibility

Access modifiers that can be specified for a class member apply equally to constructors. However, when no constructor is specified, the default constructor inserted by the compiler implicitly follows the accessibility of the class.

Accessibility of members declared in an enum type is analogous to those declared in a class, except for enum constants that are always public and constructors that are always private. A protected member in an enum type is only accessible in its own package, since an enum type is implicitly final. Member declarations in an enum type are discussed in §5.13, p. 290.

In contrast, the accessibility of members declared in an interface is always implicitly public (§5.6, p. 238). Omission of the public access modifier in this context does not imply package accessibility.

Leave a Reply

Your email address will not be published. Required fields are marked *