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

 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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.