Return to index

 

Methods

 

Object communication and interaction

 

It is through interactions among objects that programmers get the behavior their programs were designed for. 

Software objects can communicate with each other in two ways:

  • by calling ('invoking') each other's methods
  • or by directly accessing their variables.

 

Calling a method

 

Object A can call a method in object B to have it to perform some behavior or return some value.  This is also sometimes referred to as A 'sending a message' to B.

For example, when the play button is pressed on an MP3 player application, the button object may call the play() method of the application object with the understanding that this means to play the current track.

Sometimes the called object's method needs additional information in order to perform its task.  If your MP3 player application had multiple buttons, each of which played a different track, then the play() method would also need to know the number of the track to play.  This information would be passed along as a parameter ('argument') when calling the method. For example, play(3)

There are three parts to a method call statement:

  1. The object you are calling that implements the method (e.g., an MP3 player object mp3App)
  2. The name of the method to perform (e.g., play)
  3. Any arguments needed by the called object (e.g., the CD track number, 3)

The syntax for making a method call is to list the object to be called, followed by a period ('.'), then the method name.  Any arguments required are enclosed in parentheses after the method name. If no parameters are required an empty pair of parentheses is still written, to make it clear that it is a method name.

The statement to request the mp3App object to play track 3 would be:

mp3App.play(3);

It is very common for an object's methods to call other (sub)methods in its own class.  For example, suppose that the MP3 player application was playing through a play list and it was time to play the third song in the list.  The application object would need to call its own play() message, passing the number of the track to play.  The statement to do this would be:

this.play(3);

or more commonly :

play(3);

The special keyword 'this' always refers to the object whose code is currently executing.  In the second case there is no object specified.  If a method is called without an explicit object, it is assumed to be 'this' object (that is, the object is calling one of its own methods).

 

Accessing a variable

 

Sometimes object A needs to learn something about the state of object B. Because an object's state is generally stored in instance variables, objects sometimes need access to each other's instance variables. 

While it is generally considered best to call an 'accessor method' (a method that basically just returns the value of a variable) to get information about another object's state, sometimes an instance variable can or must be accessed directly.

Accessing an instance variable is similar to calling a method.  You need to specify:

  1. The object whose variable you want
  2. The name of the variable

The syntax for referencing an instance variable is to list the object to call, followed by a period ('.'), then the variable name.

The statement to get the current track of the mp3App object would be:

int track=mp3App.currentTrack;

We can do this if the variable currentTrack is public. Otherwise we would need to call the accessor method likely to be named getCurrentTrack() if this method exists.

As discussed with calling methods above, it is also very common for an object to access its own instance variables.  In this case, you can either use the 'this' keyword, or more commonly just specify the variable by itself.  Code to do this would look like:

this.currentTrack

or

currentTrack

 

Using static variables and static methods

 

Calling a static method or accessing a static variable is similar to calling an instance method or accessing an instance variable.  However, where you would normally specify the instance object you instead specify the class. 

For example, the class Color in the java.awt package has a number of useful static variables and methods that you will often use.  To access the static variable holding the color 'red', you would type:

Color.red

Likewise to call Color's static method that creates a Color instance using hue, saturation and brightness you would call:

Color.getHSBColor(0.5f, 1.0f, 1.0f)

 

Methods - Creation and Use

 

Methods are named blocks of code that can be called from elsewhere.

Methods must be defined within the body of a class.

package projects.turtles;

import com.kinabaloo.turtle.*;

public class MyTurtle extends TurtleFrame {

// Class body - methods and variables go in here

}

 

Calling methods is a mainstay of code writing. We will frequently call methods in the standard Java class library. We may also write and call our own methods.

For example, suppose we wanted to create a method called drawSquare() that draws a square on the screen using TJI's integrated Turtle Graphics (you can find 10 example projects on the 'Resources' page of our web site).  Here's one way to define the method:

private void drawSquare() {

turtle.forward(30);

turtle.turnRight(90);

turtle.forward(30);

turtle.turnRight(90);

turtle.forward(30);

turtle.turnRight(90);

turtle.forward(30);

}

 

The 'turtle' that does the drawing is turned at right angles 3 times and proceeds forward 30 pixels four times to create all four sides of the square.

The method definition is:

private void drawSquare()

Let's look more closely at the various parts of the definition.

First off,  all methods must belong to some class.  This means that 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.

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.

The third word is the name of the method itself, in this case drawSquare.  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.

The opening and closing parentheses after the method name mark the area where you would specify any parameters the method requires.  In this case there are no 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 statements 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 drawSquare() certainly works, but it is not as useful as it might be.  What if you wanted to draw a different-sized square?  To make the method more general, we can change the definition to take a parameter (also called an argument) for the size of the square.

private void drawSquare(int size) {

turtle.forward(size);

turtle.turnRight(90);

turtle.forward(size);

turtle.turnRight(90);

turtle.forward(size);

turtle.turnRight(90);

turtle.forward(size);

}

 

In this case, we specify a single parameter that will define the size of the square.  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.  We have changed all the forward() calls to use the size variable rather than the fixed value of 30 as in the first example.

If you need to specify more than one parameter to a method, you would separate them with commas.  For example, if you also wanted to be able to specify the color of the square you can define this version of the method as:

private void drawSquare(int size, Color color) {

turtle.setColor(color);

turtle.forward(size);

turtle.turnRight(90);

turtle.forward(size);

turtle.turnRight(90);

turtle.forward(size);

turtle.turnRight(90);

turtle.forward(size);

}

 

A little thought reveals that there is repetition in this method that can be reduced with the use of a for loop:

private void drawSquare(int size) {

for (int side=1; side<=4; side=side+1) {

turtle.forward(size);

turtle.turnRight(90);

}

}

 

Now that we have created our drawSquare() method, we can call it whenever we need to draw a square. Here is a code snippet that will draw three squares side by side. We'll use a while loop this time.

public void run() {

int size = 50;

int loop=1;

while (loop<=3) {

turtle.gotoXY(100+loop*60, 100);

drawSquare(size);

}

}

 

Flow of Execution

 

Here is a complete class incorporating the method drawSquare()

import com.kinabaloo.turtle.*;

public class MyTurtle extends TurtleFrame {

Turtle turtle;

 

public MyTurtle() { //constructor

turtle=createTurtle();

run();

}

 

public void run() {

int size = 50;

int loop=1;

while (loop<=3) {

turtle.gotoXY(100+loop*60, 100);

drawSquare(size);

}

}

 

private void drawSquare(int size) {

for (int side=1; side<=4; side=side+1) {

turtle.forward(size);

turtle.turnRight(90);

}

}

 

public static void main(String[] args) {

new MyTurtle();

}

}

 

Method public static void main(String[] args) is called by the Java Virtual Machine (JVM) to start the program. In turn, main() calls new MyTurtle() to create an instance of our class MyTurtle by calling the constructor MyTurtle().

Constructor MyTurtle() calls the 'factory' method createTurtle() defined in class TurtleFrame that our class extends to get a new Turtle instance. Then the constructor calls method run().

Method run() involves a loop that loops 3 times, each time calling our method drawSquare() to draw a square in a different location (as specified by the call gotoXY()).

Method drawSquare() calls the methods forward() and turnRight() defined in class Turtle, a class in package com.kinabaloo.turtle that we have imported (TJI's Turtle Graphics package).

 

NOTE: The order of the method declarations is unimportant to the execution of the code.  The sequence in which statements are executed in the program is unrelated to the ordering of the methods.

 

Method Returns

 

Let's take a quick look at how to write a method that does return a value. The return type must be declared (int in the example below) and the keyword return used to declare the actual return value. Here's a simple example :

public int add(int a, int b) {

return a+b;

}

 

Access Modifiers

 

Finally, let's take a look at the complete list of access modifiers and their meaning.

Modifier
Meaning
<none>
The variable may be accessed only by other classes in the same package (code library).
public
The variable may be accessed by any class, even if in another package.
private
The variable may be accessed only from within this class.
protected
The variable may be accessed only by other classes in the same package and by their subclasses.

These access modifiers can also be used in variable declarations.

 

Return to index