Java Reference
In-Depth Information
1
// Fig. 3.5: Account.java
2
// Account class with a constructor that initializes the name.
3
4
public class
Account
5
{
6
private
String name;
// instance variable
7
8
// constructor initializes name with parameter name
public
Account(String name)
// constructor name is class name
{
this
.name = name;
}
9
10
11
12
13
14
// method to set the name
15
public void
setName(String name)
16
{
17
this
.name = name;
18
}
19
20
// method to retrieve the name
21
public
String getName()
22
{
23
return
name;
24
}
25
}
// end class Account
Fig. 3.5
|
Account
class with a constructor that initializes the
name
.
Account
Constructor Declaration
Lines 9-12 of Fig. 3.5 declare
Account
's constructor. A constructor
must
have the
same name
as the class. A constructor's
parameter list
specifies that the constructor requires one or more
pieces of data to perform its task. Line 9 indicates that the constructor has a
String
param-
eter called
name
. When you create a new
Account
object (as you'll see in Fig. 3.6), you'll pass
a person's name to the constructor, which will receive that name in the parameter
name
. The
constructor will then assign
name
to
instance
variable
name
in line 11.
Error-Prevention Tip 3.2
Even though it's possible to do so, do not call methods from constructors. We'll explain this
in Chapter 10, Object-Oriented Programming: Polymorphism and Interfaces.
Parameter
name
of Class
Account
's Constructor and Method
setName
Recall from Section 3.2.1 that method parameters are local variables. In Fig. 3.5, the con-
structor and method
setName
both have a parameter called
name
. Although these param-
eters have the same identifier (
name
), the parameter in line 9 is a local variable of the
constructor that's
not
visible to method
setName
, and the one in line 15 is a local variable
of
setName
that's
not
visible to the constructor.
Created
The
AccountTest
program (Fig. 3.6) initializes two
Account
objects using the construc-
tor. Line 10 creates and initializes the
Account
object
account1
. Keyword
new
requests