Java Reference
In-Depth Information
The output of this program is as follows:
Started with 0 instances
Created 500 instances
This example demonstrates several features. In line 2, a private class variable is
declared to hold the number of instances. It is a class variable (declared static ) because
the number of instances is relevant to the class as a whole, not to any particular instance,
and it's private so that it can be retrieved only with an accessor method.
Note the initialization of numInstances . Just as an instance variable is initialized when
its instance is created, a class variable is initialized when its class is created. This class
initialization happens essentially before anything else can happen to that class, or its
instances, so that the class in the example will work as planned.
In lines 4-6, a get method is defined so that the private instance variable's value can be
retrieved. This method also is declared as a class method because it applies directly to
the class variable. The getCount() method is declared protected , as opposed to public ,
because only this class and perhaps its subclasses are interested in that value; other ran-
dom classes are, therefore, restricted from seeing it.
Note that there is no accessor method to set the value. The value of the variable should
be incremented only when a new instance is created; it should not be set to any random
value. Instead of creating an accessor method, a special private method called
addInstance() is defined in lines 8-10 that increments the value of numInstances by 1.
Lines 12-14 create the constructor method for this class. Constructors are called when a
new object is created, which makes this the most logical place to call addInstance() and
to increment the variable.
The main() method indicates that you can run this as a Java application and test all the
other methods. In the main() method, 10 instances of the InstanceCounter class are
created and then the value of the numInstances class variable is displayed.
Final Classes, Methods, and Variables
The final modifier is used with classes, methods, and variables to indicate that they
will not be changed. It has different meanings for each thing that can be made final, as
follows:
A final class cannot be subclassed.
n
A final method cannot be overridden by any subclasses.
n
A final variable cannot change in value.
n
 
Search WWH ::




Custom Search