Creating Behavior with Methods

Attributes are the way to keep track of information about a class of objects, but they don't take any action. For a class to actually do the things it was created to do, you must create behavior. Behavior describes all of the different sections of a class that accomplish specific tasks. Each of these sections is called a method. You have been using methods throughout your programs up to this point without knowing it, including one in particular: println(). This method displays text onscreen. Like variables, methods are used in connection with an object or a class. The name of the object or class is followed by a period and the name of the method, as in screen2D.drawString() or Integer.parseInt().

By the Way

The System.out.println() method might seem confusing because it has two periods instead of one. This is because two classes are involved in the statement—the System class and the PrintStream class. The System class has a variable called out that is a PrintStream object. println() is a method of the PrintStream class. The System.out.println() statement means, in effect, "Use the println() method of the out variable of the System class." You can chain together references to variables and methods in this way.

Declaring a Method

You create methods with a statement that looks similar to the statement that begins a class. Both can take arguments between parentheses after their names, and both use { and } marks at the beginning and end. The difference is that methods can send back a value after they are handled. The value can be one of the simple types such as integers or Boolean values, or it can be a class of objects. If a method should not return any value, use the statement void. The following is an example of a method the Virus class can use to infect files:

public boolean infectFile(String filename) {
 boolean success = false;
 // file-infecting statements would be here
 return success;

The infectFile() method is used to add a virus to a file. This method takes a single argument, a string variable called filename, and this variable represents the file that should be attacked. The actual code to infect a file is omitted here due to the author's desire to stay on the good side of the U.S. Secret Service. The only thing you need to know is that if the infection is a success, the success variable is set to a value of TRue. By looking at the statement that begins the method, you can see boolean preceding the name of the method, infectFile. This statement signifies that a boolean value will be sent back after the method is handled. The return statement is what actually sends a value back. In this example, the value of success is returned. When a method returns a value, you can use the method as part of an assignment statement. For example, if you created a Virus object called malaria, you could use statements such as these:

if (malaria.infectFile(currentFile))
 System.out.println(currentFile + " has been infected!");
 System.out.println("Curses! Foiled again!");

Any method that returns a value can be used at any place a value or variable could be used in a program. Earlier in the hour, you switched the newSeconds variable to private to prevent it from being set by other programs. However, because you're a virus writer who cares about people, you still want to make it possible for newSeconds to be used if it is used correctly. The way to do this is to create public methods in the Virus class that read the value of newSeconds or write a new value to newSeconds. These new methods should be public, unlike the newSeconds variable itself, so they can be called by other programs. The new methods will be able to work with newSeconds because they are in the same class as the variable. Consider the following two methods:

public int getSeconds() {
 return newSeconds;
public void setSeconds(int newValue) {
 if (newValue > 60)
 newSeconds = newValue;

The getSeconds() method is used to send back the current value of newSeconds. The getSeconds() method is necessary because other programs can't even look at a private variable such as newSeconds. The getSeconds() method does not have any arguments, but it still must have parentheses after the method name. Other wise, when you were using getSeconds in a program, the method would look no different than a variable. The setSeconds() method takes one argument, an integer called newValue. This integer contains the value that a program wants to change newSeconds to. If newValue is greater than 60, the change will be made. The setSeconds() method has void preceding the method name, so it does not return any kind of value. In this example, the Virus class controls how the newSeconds variable can be used by other classes. This process is called encapsulation, and it's a fundamental concept of object-oriented programming. The better your objects are able to protect themselves against misuse, the more useful they will be when you use them in other programs.

Similar Methods with Different Arguments

As you have seen with the setSeconds() method, you can send arguments to a method to affect what it does. Different methods in a class can have different names, but methods can also have the same name if they have different arguments. Two methods can have the same name if they have a different number of arguments, or the specific arguments are of different variable types. For example, it might be useful for the Virus class of objects to have two tauntUser() methods. One could have no arguments at all and would deliver a generic taunt. The other could specify the taunt as a string argument. The following statements could implement these methods:

void tauntUser() {
 System.out.println("The problem is not with your set, but "
 + "with yourselves.");
void tauntUser(String taunt) {

Constructor Methods

When you want to create an object in a program, the new statement is used, as in the following example:

Virus typhoid = new Virus();

This statement creates a new Virus object called typhoid. When you use the new statement, a special method of that object's class is called. This method is called a constructor because it handles the work required to create the object. The purpose of a constructor is to set up any variables and other things that need to be established for the object to function properly. Constructor methods are defined like other methods, except that they cannot return a value as other methods do. The following are two constructor methods for the Virus class of objects:

public Virus() {
 author = "Ignoto";
 maxFileSize = 30000;
public Virus(String name, int size) {
 author = name;
 maxFileSize = size;

Like other methods, constructors can use the arguments they are sent as a way to define more than one constructor in a class. In this example, the first constructor would be called when a new statement such as the following is used:

Virus mumps = new Virus();

The other constructor could be called only if a string and an integer were sent as arguments with the new statement, as in this example:

Virus rubella = new Virus("April Mayhem", 60000);

If you don't include any constructor methods in a class, it will inherit a single constructor method with no arguments from its superclass. There also might be other constructor methods that it inherits, depending on the superclass used. In any class, there must be a constructor method that has the same number and type of arguments as the new statement that's used to create objects of that class. In the example of the Virus class, which has Virus() and a Virus(String name, int size) constructors, you only could create Virus objects with two different types of new statements: one without arguments and one with a string and an integer as the only two arguments.

Class Methods

Like class variables, class methods are a way to provide functionality associated with an entire class instead of a specific object. Use a class method when the method does nothing that affects an individual object of the class. One example that you have used in a previous hour was the parseInt() method of the Integer class. This method is used to convert a string to a variable of the type int, as in the following:

int time = Integer.parseInt(timeText);

To make a method into a class method, use static in front of the method name, as in the following:

static void showVirusCount() {
 System.out.println("There are " + virusCount + " viruses.");

The virusCount class variable was used earlier to keep track of how many Virus objects have been created by a program. The showVirusCount() method is a class method that displays this total, and it should be called with a statement such as the following:


Variable Scope within Methods

When you create a variable or an object inside a method in one of your classes, it is usable only inside that method. The reason for this is the concept of variable scope. Scope is the section in which a variable exists in a program. If you go outside of the part of the program defined by the scope, you can no longer use the variable. The { and } statements in a program define the boundaries for a variable. Any variable created within these marks cannot be used outside of them. For example, consider the following statements:

if (numFiles < 1) {
 String warning = "No files remaining.";

This example does not work correctly because the warning variable was created inside the brackets of the if block statement. Those brackets define the scope of the variable. The warning variable does not exist outside of the brackets, so the System.out.println() method cannot use it as an argument. When you use a set of brackets inside another set of brackets, you'll need to pay attention to the scope of the variables with which you are working. Take a look at the following example:

if (infectedFiles < 5) {
 int status = 1;
 if (infectedFiles < 1) {
 boolean firstVirus = true;
 status = 0;
 } else {
 firstVirus = false;

In this example the status variable can be used anywhere, but the firstVirus variable will cause a compiler error. Because firstVirus is created within the scope of the if (infectedFiles < 1) statement, it doesn't exist inside the scope of the else statement that follows. To fix the problem, firstVirus must be created outside both of these blocks so that its scope includes both of them. One solution would be to create firstVirus at the same time that status is created. Rules that enforce scope make programs easier to debug because scope limits the area in which a variable can be used. This reduces one of the most common errors that can crop up in many coding languages: the same variable being used two different ways in different parts of a program. By enforcing restrictive rules for a variable's scope, the Java language makes it more difficult to misuse a variable. The concept of scope applies to methods also, because they are defined by an opening bracket and closing bracket. A variable created inside a method cannot be used in other methods. You can only use a variable in more than one method if it was created as an object variable or class variable after the class statement at the beginning of the program.