prev | TOC | next

Methods - Creation and Use

files: Box2.java (help)


As discussed previously, methods are named blocks of code that can be called from elsewhere in your program in order to accomplish some task.  You have already been using some pre-defined methods in your code.  For example, in the  code snippet:

penDown();
forward(100);
right(90);


you are calling three methods in the Turtle class.  Because your turtle is a subclass of Turtle, your turtle inherits these methods and can call them without explicitly specifying the target object (which is itself).  Two of these methods (forward and penDown) take additional numbers called arguments that indicate exactly what the method is to do or how it is to do it. 

In addition to using pre-defined methods, you can create your own methods in your turtle's code.  You can then call these methods to have them execute. 

For example, suppose we wanted to create a method called box that draws a simple box.  Here's one way to define the method:

private void box()
{
    forward(30);
    right(90);
    forward(30);
    right(90);
    forward(30);
    right(90);
    forward(30);
    right(90);
}
Let's look at this a bit more closely to see what the various pieces of the definition are.

First off,  all methods must belong to some class.  This means the code must be between the opening and closing "curly braces" of the class definition (this is usually the first "{" and the last "}" in the file for that class).

The first word of the declaration is the access modifier private.  This keyword means that the method can only be called from within the class in which it is defined.  This is opposed to public which means that the method can be called from other classes.  Helper methods for use within a class are generally private.  Access modifiers for methods are identical to those for member variables as discussed in Lesson 9: Anatomy of a Class File.

The next word is void.  This means that the method doesn't return any value to the code that calls it.  If the method did return a value, you would put the data type of the returned value here.  For example, you could define a method called isItAWeekday that returned a boolean value, true if it is Monday thru Friday, and false otherwise.  This definition would look like:

private boolean isItAWeekday()
{
    ....
}


The actual code for determining whether it was a weekday or not would go where the "..." are.

Back to the box example above.  The third word is the name of the method itself, in this case box.  Method names are subject to the same rules as variable names.  A method name can be any legal identifier as long as it is not a Java reserved word.  Identifiers can be any number of characters but must start with a letter (lower case by convention).  They also must not contain spaces or most other non-alphanumeric characters.  In place of space, you can substitute the underscore character "_".

The opening and closing parentheses after the method name marks the area where you would specify any parameters the method requires.  In this case there are not any parameters so there is nothing between the open and closing parentheses.

The next line has the opening "{" which starts the code block for the method.  Any code you place after this until the matching closing "}" will be part of the method and will be executed when the method is called.

Method parameters

The above definition of box certainly works, but it is not as useful as it might be.  What if you wanted to draw a different-sized box?  To make the method more general, we change the definition to take a parameter (also called an argument) i.e., the size of the box.

private void box2(int size)
{
forward(size);
right(90);
forward(size);
right(90);
forward(size);
right(90);
forward(size);
right(90);
}


In this case, we specify a single parameter which will be the size of the box.  As mentioned above, parameters are specified between the opening and closing parentheses after the method's name.  The first word int specifies the data type of the parameter, and the second word size specifies a variable name by which the parameter can be referred to in the method's code.  Note that we have changed all the forward() calls to use the size variable rather than the fixed 30 in the first example.

If you wanted to specify more arguments to a method, you would separate them by commas.  For example, if you also wanted to be able to specify the color of the box you might define it as:

private void box3(int size, Color myColor)
{
    setPenColor(myColor);
    forward(30);
    right(90);
    forward(30);
    right(90);
    forward(30);
    right(90);
    forward(30);
    ßright(90);
}

Using a method

Now that we have created a box method, how would you use it?  Here is a code snippet that will create a stack of boxes.

public void runTurtle()
{
    int size = 50;
    while (size > 2)
    {
        setAutoUpdatePause(50);
        box2(size);
        forward(size);
        size = (int)(size * 0.6);
    }
    hideTurtle();
}

Exercises

The class BoxesOnBoxes in the Examples directory contains a working turtle that defines a box method and uses it to create a stack of boxes.  Study the code to make sure you understand what it is doing, and practice by making modifications to it.

The classes PolySpiral and Circles also define and use helper methods.  Study them to understand how they accomplish what they do.