Using Class Methods and Variables

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.

Listing 11.1. The Full Text of

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

Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.