Declaring static Fields
What you'll learn: You'll learn the exact syntax for declaring static fields and how they are shared across all instances of a class.
The Syntax
Now that you understand what static means—that it belongs to the class rather than any single instance—let's see how to actually declare a static field.
The syntax is simple: place the static keyword between the access modifier and the type:
public class Counter {
private static int count; // static field
private int instanceValue; // regular instance field
}
Notice the difference:
static int countis shared by allCounterobjectsint instanceValueis unique to eachCounterobject
How Static Fields Are Shared
Think of a static field like a classroom whiteboard—there's only one board that all students share. Each student doesn't get their own whiteboard.
public class BankAccount {
private static int totalAccounts = 0;
private double balance;
}
In this example:
totalAccountsexists once, no matter how manyBankAccountobjects you create- Every
BankAccountinstance can see and modify the sametotalAccountsvalue - Each
BankAccounthas its own separatebalance
Where Static Fields Live
Static fields are stored in memory when the class is loaded, not when objects are created. They exist even if you never create a single instance of the class.
Key Takeaway: Declare a static field by placing the static keyword before the type; that field will be shared across all instances of the class, living at the class level rather than in each object.