ptg7068951
Using Class Methods and Variables 149
Listing 11.1 The Full Text of Virus.java
1: public classVirus {
2: static intvirusCount = 0;
3:
4: publicVirus() {
5: virusCount++;
6: }
7:
8: static intgetVirusCount() {
9: returnvirusCount;
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 Virusobjects.
The VirusLabclass is a simple application that creates Virusobjects and
then counts the number of objects that have been created with the
getVirusCount()class method of the Virusclass.
Open a new file with your word processor and enter Listing 11.2. Save the
file as VirusLab.javawhen you’re done.
Listing 11.2 The Full Text of VirusLab.java
1: public classVirusLab {
2: public staticvoidmain(String[] args) {
3: int numViruses = Integer.parseInt(args[0]);
4: if (numViruses > 0) {
5: Virus[] virii = new Virus[numViruses];
6: for (inti = 0; i < numViruses; i++) {
7: virii[i] = new Virus();
8: }
9: System.out.println(“There are “+ Virus.getVirusCount()
10: + “ viruses.”);
11: }
12: }
13: }
The VirusLabclass is an application that takes one argument when you
run it at the command line: the number of Virusobjects to create. To speci-
fy the command-line argument in NetBeans, do the following:
- Choose Run, Set Project Configuration, Customize. The Project
Properties dialog opens.