Java Reference
In-Depth Information
2.
Next, method
setName
performs its task—that is, it assigns the
name
parameter's
value to instance variable
name
(line 12 of Fig. 3.1).
3.
When program execution reaches
setName
's closing right brace, it returns to where
setName
was called (line 21 of Fig. 3.2), then continues at line 22 of Fig. 3.2.
The number of
arguments
in a method call
must
match
the number of
parameters
in
the method declaration's parameter list. Also, the argument types in the method call must
be
consistent
with the types of the corresponding parameters in the method's declaration.
(As you'll learn in Chapter 6, an argument's type and its corresponding parameter's type
are
not
required to be
identical
.) In our example, the method call passes one argument of
type
String
(
theName
)—and the method declaration specifies one parameter of type
String
(
name
, declared in line 10 of Fig. 3.1). So in this example, the type of the argument
in the method call
exactly
matches the type of the parameter in the method header.
Displaying the Name That Was Entered by the User
Line 22 of Fig. 3.2 outputs a blank line. When the second call to method
getName
(line 26)
executes, the name entered by the user in line 20 is displayed. When the statement at lines
25-26 completes execution, the end of method
main
is reached, so the program terminates.
You must compile the classes in Figs. 3.1 and 3.2 before you can
execute
the app. This is
the first time you've created an app with
multiple
classes. Class
AccountTest
has a
main
method; class
Account
does not. To compile this app, first change to the directory that
contains the app's source-code files. Next, type the command
javac Account.java AccountTest.java
to compile
both
classes at once. If the directory containing the app includes
only
this app's
files, you can compile both classes with the command
javac *.java
The asterisk (
*
) in
*.java
indicates that
all
files in the
current
directory ending with the
filename extension “
.java
” should be compiled. If both classes compile correctly—that is,
no compilation errors are displayed—you can then run the app with the command
java AccountTest
and
get
Methods
We'll often use UML class diagrams to summarize a class's
attributes
and
operations
. In in-
dustry, UML diagrams help systems designers specify a system in a concise, graphical, pro-
gramming-language-independent manner, before programmers implement the system in
a specific programming language. Figure 3.3 presents a
UML class diagram
for class
Ac-
count
of Fig. 3.1.
Top Compartment
In the UML, each class is modeled in a class diagram as a rectangle with three compart-
ments. In this diagram the
top
compartment contains the
class name
Account
centered hor-
izontally in boldface type.