Java Reference
In-Depth Information
So, to execute the DrawFigures3 program, the computer first executes its main
method. That, in turn, first executes the body of the method drawDiamond .
drawDiamond executes the methods drawCone and drawV (in that order). When
drawDiamond finishes executing, control shifts to the next statement in the body of
the main method: the call to the drawX method.
A complete breakdown of the flow of control from static method to static method
in DrawFigures3 follows:
1st main
2nd
drawDiamond
3rd
drawCone
4th
drawV
5th
drawX
6th
drawV
7th
drawCone
8th
drawRocket
9th
drawCone
10th
drawBox
11th
drawBox
12th
drawCone
Recall that the order in which you define methods does not have to parallel the
order in which they are executed. The order of execution is determined by the body
of the main method and by the bodies of methods called from main . A static method
declaration is like a dictionary entry—it defines a word, but it does not specify how
the word will be used. The body of this program's main method says to first execute
drawDiamond , then drawX , then drawRocket . This is the order of execution, regard-
less of the order in which the methods are defined.
Java allows you to define methods in any order you like. Starting with main at the
top and working down to lower and lower-level methods is a popular approach to
take, but many people prefer the opposite, placing the low-level methods first and
main at the end. Java doesn't care what order you use, so you can decide for yourself
and do what you think is best. Consistency is important, though, so that you can eas-
ily find a method later in a large program.
It is important to note that the programs DrawFigures1 , DrawFigures2 , and
DrawFigures3 produce exactly the same output to the console. While DrawFigures1
may be the easiest program for a novice to read, DrawFigures2 and particularly
DrawFigures3 have many advantages over it. For one, a well-structured solution is
easier to comprehend, and the methods themselves become a means of explaining the
program. Also, programs with methods are more flexible and can more easily be
adapted to similar but different tasks. You can take the seven methods defined in
DrawFigures3 and write a new program to produce a larger and more complex out-
put. Building static methods to create new commands increases your flexibility with-
out adding unnecessary complication. For example, you could replace the main
Search WWH ::




Custom Search