Java Reference
In-Depth Information
b==c
evaluates to false. The contents of variables
b
and
c
are being compared, not the
contents of the folders whose names they contain, and they contain different
names.
To be able to compare the contents of the folders named by
b
and
c
, we
define a boolean function
equals
in class
Employee
:
/** = "
This
Employee
and
e
contain the same fields
" */
public boolean
equals(Employee e) {
return this
.name == e.name
&&
this
.start == e.start
&&
this
.salary == e.salary;
}
Later, in Sec. 4.3.2, when we have defined the subclass and class
Object
, we will
revisit function
equals
and write it slightly differently.
Given the situation in Fig. 3.4, suppose we execute the assignment
b= c;
Then,
b
and
c
both contain the name
a5
:
b a5
c a5
and we can get the name of the person using
b.getName()
and c.getName() —
we have two ways of referencing the components. This is called
aliasing
because
variables
b
and
c
refer to the same object.
In the real world, aliasing often has negative connotations —crooks mas-
querade under several aliases to stay ahead of the law.
In object-oriented programming, aliasing is a natural occurrence. In terms of
our model of file drawers and folders, it makes sense. Barbara (variable
b
), the
person in charge of salaries for a company, might change
a5
's salary. Charles
(variable
c
), an administrative aide, might later change the name of the person in
folder
a5
to fix a mistake.
You, the programmer, must be aware of this phenomenon of aliasing in order
to design and develop correct programs.
3.2.5
Making fields public
Consider class
Coordinates
of Fig. 3.5, whose sole purpose is to aggregate the
x
-coordinate and
y
-coordinate of a point
(x, y)
in the plane. It has two fields,
which are public, and only two methods, a constructor and function
toString
.
This class exists not so much for its behavior but simply as a way to collect
two values in one place —in an instance. In fact, we could remove the two meth-
ods and still find the class useful. The class (or its instances) is similar to the lan-
guage Pascal's
record
and the language C's
struct
.
Search WWH ::
Custom Search