1.5. Static Members

In some cases, certain members should only belong to the class, and not be part of any object created from the class. An example of such a situation is when a class wants to keep track of how many objects of the class have been created. Defining a counter as an instance variable in the class definition for tracking the number of objects created, does not solve the problem. Each object created will have its own counter field. Which counter should then be updated? The solution is to declare the counter field as being static. Such a field is called a static variable. It belongs to the class, and not to any object of the class. A static variable is initialized when the class is loaded at runtime. Similarly, a class can have

Get Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second 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.