Java Reference
In-Depth Information
Code 2.9
continued
The
Student
class
/**
* Return the number of credit points this student
* has accumulated.
*/
public
int
getCredits()
{
return
credits;
}
/**
* Return the login name of this student.
* The login name is a combination
* of the first four characters of the
* student's name and the first three
* characters of the student's ID number.
*/
public
String getLoginName()
{
return
name.substring(0,4) +
id.substring(0,3);
}
/**
* Print the student's name and ID number
* to the output terminal.
*/
public
void
print()
{
System.out.println(name +
", student ID: "
+ id +
", credits: "
+ credits);
}
}
In this small example, the pieces of information we wish to store for a student are their name,
their student ID, and the number of course credits they have obtained so far. All of this infor-
mation is persistent during their time as a student, even if some of it changes during that time
(the number of credits). We want to store this information in fields, therefore, to represent each
student's state.
The class contains three fields:
name
,
id
, and
credits
. Each of these is initialized in the single
constructor. The initial values of the first two are set from parameter values passed into the con-
structor. Each of the fields has an associated
get
accessor method, but only
name
and
credits
have associated mutator methods. This means that the value of an
id
field remains fixed once
the object has been constructed. If a field's value cannot be changed once initialized, we say
that it is
immutable
. Sometimes we make the complete state of an object immutable once it has
been constructed; the String class is an important example of this.
Search WWH ::
Custom Search