Java Reference
In-Depth Information
technique for calculating hash codes, but we recommend the interested reader to see Joshua
Bloch's
Effective Java
, whose technique we use here.
4
Essentially, an integer value should be
computed making use of the values of the fields that are compared by the overridden
equals
method. Here is a hypothetical
hashCode
method that uses the values of an integer field called
count
and a
String
field called
name
to calculate the code:
public int hashCode()
{
int result = 17; // An arbitrary starting value.
// Make the computed value depend on the order in which
// the fields are processed.
result = 37 * result + count;
result = 37 * result + name.hashCode();
return result;
}
9.9
Protected access
In Chapter 8, we noted that the rules on public and private visibility of class members apply
between a subclass and its superclass, as well as between classes in different inheritance hier-
archies. This can be somewhat restrictive, because the relationship between a superclass and
its subclasses is clearly closer than it is with other classes. For this reason, object-oriented lan-
guages often define a level of access that lies between the complete restriction of private access
and the full availability of public access. In Java, this is called
protected access
and is provided
by the
protected
keyword as an alternative to
public
and
private
. Code 9.5 shows an
example of a protected accessor method, which we could add to class
Post
.
Concepts:
Declaring a field or a
method
protected
allows direct access
to it from (direct or
indirect) subclasses.
Code 9.5
An example of a
protected method
protected
long
getTimeStamp()
{
return
timestamp;
}
Protected access allows access to the fields or methods within a class itself and from all its
subclasses, but not from other classes.
5
The
getTimeStamp
method shown in Code 9.5 can be
called from class
Post
or any subclasses, but not from other classes. Figure 9.8 illustrates this.
The oval areas in the diagram show the group of classes that are able to access members in class
SomeClass
.
4
At the time of writing, sample chapters that contain material relevant to this topic are available at
5
In Java, this rule is not as clear-cut as described here, because Java includes an additional level of vis-
ibility, called
package level
, but with no associated keyword. We will not discuss this further, and it is
more general to consider protected access as intended for the special relationship between superclass
and subclass.
Search WWH ::
Custom Search