Java Reference
In-Depth Information
inside-out rule
, which in this instance makes the use of
this
unnecessary. Here
is the general rule:
General inside-out rule
: In a subpart (e.g. a method) of a con-
struct (e.g. a class), all the names that are declared or that can be
referenced in the construct can be referenced in the subpart,
unless the subpart redeclares them.
Here is the inside-out rule as it pertains to method bodies in Java:
Inside-out rule for non-static method bodies
: In a method body,
all the components of the class in which the method is defined can
be referenced, unless they are redeclared (e.g. as parameters).
This inside-out rule in Java lets us write method
toString
more simply as:
/** =
a representation of this instance
*/
public
String toString() {
return
getName() + ", year " + getStart();
}
because
getName
,
year
, and
getStart
are declared in class
Employee
.
We illustrate a case where the use of
this
is necessary. Consider writing
method
setName
using
name
for the parameter instead of
n
:
/**
Set the name of this
Employee
to
name */
public void
setName(String name)
{
this
.name= name; }
Since the parameter is named
name
,
name
cannot be used directly to refer to
field
name
. The assignment
name= name;
assigns to the parameter and not to the
field. To assign to the field, write the assignment as:
this
.name= name;
Some programmers use the convention that in a setter method, the parame-
ter name is the same as the field being set. When using this convention, the use
of keyword
this
is needed to assign to the field.
3.1.3
Declaration of constructors
Chapter 2 contains an extensive treatment of procedures and functions. Here, we
discuss the third kind of method, the
constructor
. There is one constructor in
class
Employee
, which we give here:
/**
Constructor: a person with name
n
, year hired
d
, salary
50,000 */
public
Employee(String n,
int
d) {
name= n;
start= d;
Activity
3-5.2
}
Search WWH ::
Custom Search