Java Reference
In-Depth Information
Typically, the apps you develop in this topic will consist of two or more classes. If you
become part of a development team in industry, you might work on apps that contain
hundreds, or even thousands, of classes.
In this section, you'll create two classes—
Account
(Fig. 3.1) and
AccountTest
(Fig. 3.2).
Class
AccountTest
is an
application class
in which the
main
method will create and use an
Account
object to demonstrate class
Account
's capabilities.
Method
Different accounts typically have different names. For this reason, class
Account
(Fig. 3.1)
contains a
name
instance variable
. A class's instance variables maintain data for each object
(that is, each instance) of the class. Later in the chapter we'll add an instance variable named
balance
so we can keep track of how much money is in the account. Class
Account
con-
tains two methods—method
setName
stores a name in an
Account
object and method
getName
obtains a name from an
Account
object.
1
// Fig. 3.1: Account.java
2
// Account class that contains a name instance variable
3
// and methods to set and get its value.
4
5
public class
Account
6
{
7
private
String name;
// instance variable
8
9
// method to set the name in the object
public void
setName(String name)
{
this
.name = name;
// store the name
}
10
11
12
13
14
15
// method to retrieve the name from the object
public
String getName()
{
return
name;
// return value of name to caller
}
16
17
18
19
20
}
// end class Account
Fig. 3.1
|
Account
class that contains a
name
instance variable and methods to
set
and
get
its
value.
Class Declaration
The
class declaration
begins in line 5:
public class
Account
The keyword
public
(which Chapter 8 explains in detail) is an
access modifier
. For now,
we'll simply declare every class
public
. Each
public
class declaration must be stored in a file
having the
same
name as the class and ending with the
.java
filename extension; otherwise,