Lesson 26: The static Keyword
The static keyword means that the member (variable, method, or block) belongs to the class itself, rather than to any specific instance (object) of the class.
1. Static Variables (Class Variables)
- Shared across all instances of the class.
- Initialized only once when the class is loaded into memory.
java public class Counter { // Instance variable (each object has its own copy) int instanceCount = 0;
// Static variable (shared across all objects)
public static int totalObjects = 0;
public Counter() {
instanceCount++;
totalObjects++; // Increments the shared count
}
}
Counter c1 = new Counter(); Counter c2 = new Counter();
// Access static variables via the Class name System.out.println(Counter.totalObjects); // Output: 2
2. Static Methods
- Can be called directly using the class name (e.g.,
Math.sqrt(16)). - Cannot access or modify non-static (instance) variables directly.
- Cannot use the
thisorsuperkeywords (since there is no object context).
java public static String getCompanyName() { return "TechCorp"; }
// Access: String name = Counter.getCompanyName();
3. Static Initialization Blocks
Used to initialize static variables or perform static setup logic when the class is first loaded.
java public class Config { public static final double PI;
static {
// This runs once when Config class is loaded
PI = 3.14159;
System.out.println("Static block initialized.");
}
}