Use of the Keyword Protected
[..]
[heel verhaal, yada yada yada bla bla bla] [..]
For methods (and data) there are four types of access. In increasing constraint, they are
public,
protected, "default", and
private:
- public - methods declared public are always visible. This is an ideal keyword for use in describing interfaces.
- protected - class methods declared as protected are visible to any class declared in the same package, as well as any extension to the class whether or not it is in the same package.
- "defaul" or "friendly" - class methods declared without any keyword are visible to any class declared in the same package, as well s any extension to the class whithin the same package.
- private - class methods are not visible outside of the class.
For our purposes it seems best to commit to one level of protection for the implementation:
protected. What follows is an informal defense for that decision.
First, the use of
public provides no control over the acces of methods and fields. [..]
Make it public and they will use it. Even if you don't want them to.
The use of the
private access control is far too restrictive. Suppose we are interested in constructing two types of lists - a
SimpleList and an extension, a
ComplexList. The
SimpleList has a field,
head, that references the first element of the list. Clearly, this field should be declared
protected; manipulating the head of the list without going through a method is likely to put the list into an inconsistent state. Now, suppose that the
ComplexList manipulates the list in a way that requires manipulating the head of the list in a manner not previously provided. Declaring
head to be
private makes it impossible for the
ComplexList to access the field directly. We might be tempted to provide the access through a method of
SimpleList, but
we are then forced to restate the argument as it applies to methods. If, then, we are to have an effective extension of types, the
private keyword cannot be the preferred method of access control.
If one uses the "default" access control, it is possible for any class inside, but not outside, the package to access the associated field. [..] If the concern is access to implementation information outside the package, the class should be declared
final to indicate that extension is not allowed. [..] If extension is allowed,
all extensions should have equal access.
What remains, then, is the use of the
protected access control. [..] Since all extensions are provided equal access, extensions to the package are welcomed and are likely to occur.
[..]
For most purposes, the
protected keyword is suitable. The reader should be aware, however, that its use here is not an adoption of an ideal, but an acceptance of what's available. In short, while Java is not perfect, it is a work in progress and we may reasonably expect improvements in iets access control.