CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
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. Sams.net 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 to . 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 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 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)
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!');
else
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()
void public setSeconds(int 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()
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()
public Virus(String name, int 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()
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:
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 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 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)
System.out.println(warning);
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();
chickenpox.name = 'LoveHandles';
chickenpox.setSeconds(75);
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()
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:
System.out.println(this.author);
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:
verifyData(this);
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.
Workshop: Using Class Methods and Variables
At the insistence of every attorney and management executive in the Macmillan family of computer publishers, the workshop for this hour will not be the creation of a working virus program. Instead, you'll create a simple Virus object that can do only one thing: Count the number of Virus objects that a program has created and report the total.
Load your word processor and create a new file called Virus.java. Enter Listing 11.1 into the word processor and save the file when you're done.
Listing 11.1. The full text of Virus.java.
1: public class Virus
7:
8: static int getVirusCount()
Compile the file, and then return to your word processor. You need to create a
short program that will create Virus objects and ask the Virus
class to count them. Open up a new file and enter Listing 11.2. Save the file
as VirusLook.java
when you're done.
Listing 11.2. The full text of VirusLook.java.
1: class VirusLook
Compile the VirusLook.java file, and then run it with the java interpreter by typing the following command:
java VirusLook
The output should be the following:
There are 3 viruses.
Summary
You now have completed two of the three hours devoted to object-oriented concepts in this book. You've learned how to create an object and give behavior and attributes to the object and to its own class of objects. Thinking in terms of objects is one of the tougher challenges of the Java programming language. Once you start to understand it, however, you realize that the entire language makes use of objects and classes.
During the next hour, you'll learn how to give your objects parents and children.
Q&A
Q Can
constructor methods send back a value like other methods?
A No,
because there's no way to receive that value. Unlike other methods that can be
used as part of an equation, the argument of a method, or other statements,
constructors are only handled in response to a new statement. There's no way
for that statement to receive a value that would be sent by the method.
Q Do you have to create an object to use class variables or methods?
A Because class variables and methods aren't associated with a specific
object, you don't
need to create an object solely for the purpose of using them. The use of the Integer.parseInt() method is an example of this
because you don't have to create a new Integer object just to convert a string to an int value.
Q What's the difference between the Integer object and the int variable type?
A The first is an object, and the second is a simple variable type. Each of
the variable types such as char int, and float has a corresponding object. The object is
used when you want to use an object's methods or treat the variable like an
object. Because an Integer object can do things in a program that the int variable type cannot, it is
convenient to have both.
Quiz
The following questions will test whether you have the attributes and behavior to understand object-oriented programming techniques.
Questions
What is a method an example
of in a Java class?
(a) attributes
(b) statements
(c) behavior
2. If you want to make a variable a class variable, what statement must you
use when it is created?
(a) new
(b) public
(c) static
3. What is the name for the part of a program in which a variable lives?
(a) its nest
(b) the scope
(c) variable valley
Answers
c. A method is made up of
statements, but it's an example of behavior.
2. c.
3. b.
Activities
If all this talk of viruses didn't make you sick, you can increase your knowledge of this hour's topics with the following activity:
Add a private variable to the Virus class that stores an integer called newSeconds. Create methods to return the value of newSeconds and change the value of newSeconds only if the new value is between 60 and 100.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 713
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved