static Keyword

A static member is a member of a class that isn’t associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.

The two types of static members are static fields and static methods:

check.png Static field: A field that’s declared with the static keyword, like this:

private static int ballCount;

The position of the static keyword is interchangeable with the positions of the visibility keywords (private and public, as well as protected, which I describe in the next chapter). As a result, the following statement works, too:

static private int ballCount;

As a convention, most programmers tend to put the visibility keyword first.

The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName.

Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first.

check.png Static method: A method declared with the static keyword. Like static fields, static methods are associated with the class ...

Get Java For Dummies Quick Reference 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.