Creating Behavior with Methods

Attributes are the way to keep track of information about a class of objects, but for a class to do the things it was created to do, you must create behavior. Behavior describes the parts 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().


Note

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 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.

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 go here
    return success;
}

This method takes a single argument: a string variable called filename, which is a variable that represents the file that should be attacked. If the infection is a success, the success variable is set to true.

In the statement that begins the method, boolean precedes the name of the method, infectFile. This statement signifies that a boolean value is sent back after the method is handled. The return statement is what actually sends a value back. In this method, the value of success is returned.

If a method should not return a value, use the keyword void.

When a method returns a value, you can use the method as part of an expression. 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!");
} else {
    System.out.println("Curses! Foiled again!");
}

You can use any method that returns a value at any place in the program where you could use a variable.

Earlier in the hour, you switched the newSeconds variable to private to prevent it from being read or modified by other programs. There’s still a way to make it possible for newSeconds to be used elsewhere: Create public methods in the Virus class that get the value of newSeconds and set newSeconds to a new value. These new methods should be public, unlike the newSeconds variable itself, so they can be called in other programs.

Consider the following two methods:

public int getSeconds() {
    return newSeconds;
}

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

These methods are called accessor methods because they enable the newSeconds variable to be accessed from other objects.

The getSeconds() method is used to retrieve the current value of newSeconds. The getSeconds() method does not have any arguments, but it still must have parentheses after the method name. The setSeconds() method takes one argument, an integer called newValue. This argument is the new value of newSeconds. If newValue is greater than 60, the change will be made.

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 OOP. The better your objects are able to protect themselves against misuse, the more useful they are when you use them in other programs.

Though newSeconds is private, the new methods getSeconds() and setSeconds() are able to work with newSeconds because they are in the same class.

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 also can 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 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 and would deliver a generic taunt. The other could specify the taunt as a string argument. The following statements implement these methods:

void tauntUser() {
    System.out.println("That has gotta hurt!");
}

void tauntUser(String taunt) {
    System.out.println(taunt);
}

The methods have the same name, but the arguments differ—one has no argument, the other has a single String argument. The arguments to a method are called the method’s signature. A class can have different methods with the same name as long as each method has a different signature.

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 call the methods that must take place for the object to function properly.

Constructors are defined like other methods, except they cannot return a value. The following are two constructors for the Virus class of objects:

public Virus() {
    String author = "Ignoto";
    int 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 are 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 inherits 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 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. In the previous hour, “Creating Your First Object,” you used the parseInt() method of the Integer class to convert a string to a variable of the type int:

int fontSize = Integer.parseInt(fontText);

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

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 you can call it with a statement such as the following:

Virus.showVirusCount();

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 block 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’s scope. 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.";
}
System.out.println(warning);

This code does not work—and does not compile in NetBeans—because the warning variable was created inside the brackets of the if block. 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 need to pay attention to the scope of the enclosed variables. Take a look at the following example:

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

See any problems? In this example the status variable can be used anywhere, but the statement that assigns a value to the firstVirus variable causes 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 is to create firstVirus one line after status is created.

Rules that enforce scope make programs easier to debug because scope limits the area in which you can use a variable. This reduces one of the most common errors that can crop up in programming—using the same variable two different ways in different parts of a program.

The concept of scope also applies to methods because they are defined by an opening bracket and closing bracket. A variable created inside a method cannot be used in other methods. You only can use a variable in more than one method if it was created as an object variable or class variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.245.167