Monday, October 18, 2010

Object & Methods In Java

Describing What Your Object Is Like
As you learned during last hour's introduction to object-oriented programming, an object is a way of organizing a program so that it has everything it needs to accomplish a task. Objects need two things to do their jobs: attributes and behavior.
Attributes are the information stored within an object. They can be variables such as integers, characters, Boolean values, or even other objects. Behavior is the groups of statements used to handle specific jobs within the object. Each of these groups is called a method.
Up to this point, you have been working with the methods and variables of objects without knowing it. Any time your statement had a period in it that wasn't a decimal point or part of a string, chances are an object was involved. You'll see this during this hour as the following topics are covered:
·         Creating variables for an object
·         Creating variables for a class
·         Using methods with objects and classes
·         Calling a method in a statement
·         Returning a value with a method
·         Creating constructor methods
·         Sending arguments to a method
·         Using this to refer to an object
·         Creating new objects
For the purposes of this hour's examples, you'll be looking at a class of objects called Virus whose sole purpose in life is to reproduce in as many places as possible--much like some of the people I went to college with. A Virus has several different things it needs in order to do its work, and these will be implemented as the behavior of the class. The information that's needed for the methods will be stored as attributes.

Caution: The example in this hour will not teach actual virus writing, though it might provide some insight into how virus programs work as they wreak havoc on the file systems of the computer-loving world. had scheduled Teach Yourself Virus Programming in a Three-Day Weekend for spring of this year, but the book has been postponed because the author's hard drive was unexpectedly erased on Michaelangelo's birthday.

Creating Variables
The attributes of an object represent any variables that are needed in order for the object to function. These variables could be simple data types such as integers, characters, and floating-point numbers, or they could be arrays or objects of the String or Graphics classes. An object's variables can be used throughout its program in any of the methods the object includes. You create variables immediately after the class statement that creates the class and before any methods.
One of the things that a Virus object needs is a way to indicate that a file has already been infected. Some computer viruses change the field that stores the time a file was last modified; for example, a virus might move the time from 13:41:20 to 13:41:61. Because no normal file would be saved on the 61st second of a minute, the time is a sign that the file was infected. The Virus object will use 86 as the seconds field of a file's modification time because "86 it" is slang that means to throw something away--exactly the kind of unpleasant antisocial connotation we're going for. The value will be stored in an integer variable called newSeconds.
The following statements begin a class called Virus with an attribute called newSeconds and two other attributes:
public class Virus {
    public integer newSeconds = 86;
    public String author = "Sam Snett";
    integer maxFileSize = 30000;
All three variables are attributes for the class: newSeconds, maxFileSize, and author.
The newSeconds variable has a starting value of 86, and the statement that creates it has public in front of it. Making a variable public makes it possible to modify the variable from another program that is using the Virus object. If the other program attaches special significance to the number 92, for instance, it can change newSeconds to that value. If the other program creates a Virus object called influenza, it could set that object's newSeconds variable with the following statement:
influenza.newSeconds = 92;
The author variable also is public, so it can be changed freely from other programs. The other variable, maxFileSize, can only be used within the Virus class itself.
When you make a variable in a class public, the class loses control over how that variable is used by other programs. In many cases, this might not be a problem. For example, the author variable can be changed to any name or pseudonym that identifies the author of the virus, and the only restriction is aesthetic. The name might eventually be used on court documents if you're prosecuted, so you don't want to pick a dumb one. The State of Ohio v. LoveHandles doesn't have the same ring to it as Ohio v. April Mayhem.
Restricting access to a variable keeps errors from occurring if the variable is set incorrectly by another program. With the Virus class, if newSeconds is set to a value of 60 or less, it won't be reliable as a way to tell that a file is infected. Some files may be saved with that number of seconds regardless of the virus, and they'll look infected to Virus. If the Virus class of objects needs to guard against this problem, you need to do these two things:
·         Switch the variable from public to private protected or private.
·         Add behavior to change the value of the variable and report the value of the variable to other programs.
A private protected variable can only be used in the same class as the variable or any subclasses of that class. A private variable is restricted even further--it can only be used in the same class. Unless you know that a variable can be changed to anything without affecting how its class functions, you probably should make the variable private or private protected.
The following statement makes newSeconds a private protected variable:
private protected int newSeconds = 86;
If you want other programs to use the newSeconds variable in some way, you'll have to create behavior that makes it possible. This task will be covered later in the hour.
Creating Class Variables
When you create an object, it has its own version of all the variables that are part of the object's class. Each object created from the Virus class of objects has its own version of the newSeconds, maxFileSize, and author variables. If you modified one of these variables in an object, it would not affect the same variable in another Virus object.
There are times when an attribute has more to do with an entire class of objects than a specific object itself. For example, if you wanted to keep track of how many Virus objects were being used in a program, it would not make sense to store this value repeatedly in each Virus object. Instead, you can use a class variable to store this kind of information. You can use this variable with any object of a class, but only one copy of the variable exists for the whole class. The variables you have been creating for objects thus far can be called object variables, because they are tied to a specific object. Class variables refer to a class of objects as a whole.
Both types of variables are created and used in the same way, except that static is used in the statement that creates class variables. The following statement creates a class variable for the Virus example:
static int virusCount = 0;
Changing the value of a class variable is no different than changing an object's variables. If you have a Virus object called tuberculosis, you could change the class variable virusCount with the following statement:
Because class variables apply to an entire class instead of a specific object, you can use the name of the class instead:
Both statements accomplish the same thing, but there's an advantage to using the second one. It shows immediately that virusCount is a class variable instead of an object's variable because you can't refer to object variables with the name of a class. That's only possible with class variables.
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 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 two in particular: println() in Java applications and drawString() in applets. These methods display text on-screen. 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 screen.drawString() or Integer.parseInt().
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 Booleans, 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:
boolean public 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 use newSeconds. Because these methods are public, they can be used by other programs. Because they're in the same class as newSeconds, they can modify it.

Consider the following two methods:
int public getSeconds() {
    return newSeconds;

void public 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 newSeconds because it is private. The getSeconds() method does not have any arguments, but it still must have parentheses after the method name. Otherwise, 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 61 or greater, the change will be made. The setSeconds() method has void preceding the method name, so it does not return any kind of value.
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, use the new statement, as in the following:
Virus typhoid = new Virus();
This statement creates a new Virus object called typhoid, and it uses a special method in the Virus class called a constructor. Constructors are methods that are used when an object is first being created. The purpose of a constructor is to set up any variables and other things that need to be established.
The following are two constructor methods for the Virus class of objects:
public Virus() {
    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 have more than one constructor in a class. In this example, the first constructor would be used with a statement such as the following:
Virus mumps = new Virus();
The other constructor could be used only if a string and an integer were sent as arguments, as in this statement:
Virus rubella = new Virus("April Mayhem", 60000);
If you only had the preceding two constructor methods, you could not use the new statement with any other type or number of arguments within the parentheses.
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. The variable does not exist outside of the brackets, so the System.out.println() method cannot use warning as an argument.
One of the areas that can lead to errors in a program is when a variable has a different value than you expected it to have. In a large program written with many programming languages, this area can be difficult to fix because any part of the program might use the variable. Rules that enforce scope make programs easier to debug because scope limits the area in which a variable can be used.
This concept applies to methods because 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.
Using the this Keyword
Because you can refer to variables and methods in other classes along with variables and methods in your own class, it can easily become confusing. One way to make things a little clearer is with the this statement. The this statement is a way to refer in a program to the program's own object.
When you are using an object's methods or variables, you put the name of the object in front of the method or variable name, separated by a period. Consider these examples:
Virus chickenpox = new Virus(); = "LoveHandles";
These statements create a new Virus object called chickenpox, set the name variable of chickenpox, and then use the setSeconds() method of chickenpox.
There are times in a program where you need to refer to the current object--in other words, the object represented by the program itself. For example, inside the Virus class, you might have a method that has its own variable called author:
void public checkAuthor() {
    String author = null;
A variable called author exists within the scope of the checkAuthor() method, but it isn't the same variable as an object variable called author. If you wanted to refer to the current object's author variable, you have to use the this statement, as in the following:
By using this, you make it clear which variable or method you are referring to. You can use this anywhere in a class that you would refer to an object by name. If you wanted to send the current object as an argument in a method, for example, you could use a statement such as the following:
In many cases, the this statement will not be needed to make it clear that you're referring to an object's variables and methods. However, there's no detriment to using this any time you want to be sure you're referring to the right thing.

No comments:

Post a Comment