Java Reference
In-Depth Information
• The keyword
public
indicates that this method is available to be used by all parts
of your program. All methods you write will be public.
• The keyword
static
indicates that this is a static (procedural-style, not object-
oriented) method. For now, all methods you write will be static, until you learn
about defining objects in Chapter 8.
• The keyword
void
indicates that this method executes statements but does not
produce any value. (Other methods you'll see later compute and return values.)
•
<name>
(e.g.,
drawBox
) is the name of the method.
•
The empty parentheses specify a list (in this case, an empty list) of values that are
sent to your method as input; such values are called
parameters
and will not be
included in your methods until Chapter 3.
Including the keyword
static
for each method you define may seem cumber-
some. Other Java textbooks often do not discuss static methods as early as we do
here; instead, they show other techniques for decomposing problems. But even
though static methods require a bit of work to create, they are powerful and useful
tools for improving basic Java programs.
After the header in our sample method, a series of
println
statements makes up
the body of this static method. As in the
main
method, the statements of this method
are executed in order from first to last.
By defining the method
drawBox
, you have given a simple name to this sequence
of
println
statements. It's like saying to the Java compiler, “Whenever I tell you to
'drawBox,' I really mean that you should execute the
println
statements in the
drawBox
method.” But the command won't actually be executed unless our
main
method explicitly says that it wants to do so. The act of executing a static method is
called a
method call.
Method Call
A command to execute another method, which causes all of the statements
inside that method to be executed.
To execute the
drawBox
command, include this line in your program's
main
method:
drawBox();
Since we want to execute the
drawBox
command twice (to draw two boxes), the
main
method should contain two calls to the
drawBox
method. The following
Search WWH ::
Custom Search