At the insistence of our attorney, the next project is not the creation of a working virus. Instead, you create a simple Virus
object that can count the number of Virus
objects that a program has created and report the total.
Choose File, New File in NetBeans and create a new Empty Java File called Virus
. Enter Listing 11.1 in the source editor.
1: public class Virus {
2: static int virusCount = 0;
3:
4: public Virus() {
5: virusCount++;
6: }
7:
8: static int getVirusCount() {
9: return virusCount;
10: }
11: }
Save the file, which NetBeans compiles automatically. This class lacks a main()
method and thus cannot be run directly. To test out this new Virus
class, you need to create a second class that can create Virus
objects.
The VirusLab
class is a simple application that creates Virus
objects and then counts the number of objects that have been created with the getVirusCount()
class method of the Virus
class.
Open a new file with your word processor and enter Listing 11.2. Save the file as VirusLab.java
when you’re done.
1: public class VirusLab {
2: public static void main(String[] args) {
3: int numViruses = Integer.parseInt(args[0]);
4: if (numViruses > 0) {
5: Virus[] virii = new Virus[numViruses];
6: for (int i = 0; i < numViruses; i++) {
7: virii[i] = new Virus();
8: }
9: System.out.println("There are " + Virus.getVirusCount()
10: + " viruses.");
11: }
12: }
13: }
The VirusLab
class is an application that takes one argument when you run it at the command line: the number of Virus
objects to create. To specify the command-line argument in NetBeans, do the following:
1. Choose Run, Set Project Configuration, Customize. The Project Properties dialog opens.
2. Enter VirusLab
in the Main Class field, and enter the number of Virus
objects you’d like the program to create in the Arguments field.
3. Click OK to close the dialog.
To run a program you’ve configured in this manner, choose Run, Run Main Project in NetBeans.
Arguments are read into an application using a string array that’s sent to the main()
method. In the VirusLab
class, this occurs in Line 2.
To work with an argument as an integer, it must be converted from a String
object to an integer. This requires the use of the parseInt()
class method of the Integer
class. In Line 3, an int
variable named numViruses
is created from the first argument sent to the program on the command line.
If the numViruses
variable is greater than 0, the following things take place in the VirusLab
application:
• Line 5: An array of Virus
objects is created with the numViruses
variable determining the number of objects in the array.
• Lines 6–8: A for
loop is used to call the constructor method for each Virus
object in the array.
• Lines 9–10: After all the Virus
objects have been constructed, the getVirusCount()
class method of the Virus
class is used to count the number of its objects that have been created. This should match the argument that was set when you ran the VirusLab
application.
If the numViruses
variable is not greater than 0, nothing happens in the VirusLab
application.
After the VirusLab.java
file has been compiled, test it with any command-line argument you’d like to try. The number of Virus
objects that can be created depends on the memory that’s available on your system when you run the VirusLab
application. On the author’s system, anything greater than 5.5 million viruses causes the program to crash after displaying an OutOfMemoryError
message.
If you don’t specify more Virus
objects than your system can handle, the output should be something like Figure 11.1.
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, give behavior and attributes to the object and its class of objects, and convert objects and variables into other forms by using casting.
Thinking in terms of objects is one of the tougher challenges of the Java programming language. When you start to understand it, however, you realize that the entire language makes use of objects and classes.
During the next hour, you learn how to give your objects parents and children.
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. Is there a list of all the built-in methods that Java supports?
A. Oracle offers full documentation for all classes in the Java language, including all public methods you can use, on the Web at http://download.oracle.com/javase/7/docs/api.
Q. What do I have to do to be ranked in men’s tennis?
A. There are currently 1,847 male tennis players ranked in the ATP World Tour tennis rankings. If your goal is to do at least as well as the lowest ranked player, you must reach the round of 16 in an ITF Futures tournament.
At the time of this writing, Tilen Zitnik is ranked in 1,847th place among men’s singles players. Zitnik achieved this distinction by earning only one point in the 15 tournaments he’s entered the past 52 weeks. Several hundred other players also have earned one point, but they did it in fewer tournaments.
Zitnik, a 19-year-old from Slovenia, played the Ukraine F3 futures tournament in March 2011. There was a 48-player qualifier and a 32-player field. Zitnik beat Matteo Marfa of Italy in three sets. He had the misfortune of drawing No. 1 seed Artem Smirnov of the Ukraine in the second round and lost in two sets. His year-to-date prize winnings are $1,260.
There’s probably a Futures tournament near you. More than 500 take place around the world each year. Visit www.itftennis.com for the calendar and entry information.
Good luck! If you make it, I want a share of your earnings.
The following questions see if you have the attributes and behavior to understand OOP techniques.
1. In a Java class, a method is an example of what?
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
1. C. A method is made up of statements, but it’s an example of behavior.
2. C. If the static
statement is left off, the variable is an object variable instead of a class variable.
3. B. The compiler fails with an error when a variable is used outside of its scope.
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
.
• Write a Java application that takes an argument as a string, converts it to a float variable, converts that to a Float
object, and finally turns that into an int
variable. Run it a few times with different arguments to see how the results change.
To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.
18.191.92.107