Java Reference
In-Depth Information
In addition, it should have two other properties:
• It is
consistent
:
x.equals(y)
consistently returns
true
or consistently
returns
false
, provided no information used in equals comparisons on
the object is modified.
• For any folder
x
,
x.equals(
null
)
is
false
.
The spec of function
equals
says that it is generally necessary to override
method
hashCode
whenever
equals
is overridden to maintain the general con-
tract for method
hashCode
, which states that equal objects must have equal hash
codes. But the topic of method
hashCode
is outside the scope of this text.
An example of overriding equals
In Sec. 3.2.4, we discussed aliasing and equality and wrote this boolean
function in class
Employee
:
/** = "
This
Employee
and
e
contain the same fields
" */
public boolean
equals(Employee e) {
return
name == e.name
&& start == e.start
&& salary == e.salary;
}
We now rewrite this function so that it overrides function
equals
of class
Object
. Thus, its parameter must be
Object
. Further, we must make sure that
e
is not
null
and that its real class is
Employee
. Here is the function:
/** = "e
is an
Employee
, with the same fields as this
Employee" */
public boolean
equals(Object e) {
return
e!=
null
&& e
instanceOf
Employee
&& name == e.name
&& start == e.start
&& salary == e.salary;
}
4.4
Access modifiers
This section need be studied only if you are going to write your own packages
(see Chap. 11).
As you know, a
private
component in a class
C
can be accessed only in class
C
, and not even in subclasses of
C
. A
public
component can be accessed any-
where. Classification
private
is extremely restrictive;
public
is extremely liber-
al. Java has two other access schemes, which we call
protected
and
package
, that
fall between these two extremes. Below, we list all four schemes, from least to
most restrictive:
Activity
4-2.6
Search WWH ::
Custom Search