Background:
From the very beginning, Java introduced the concept of static class members, which differ from instance members — such variables are stored at the class level, not the object level. This allows sharing data among all instances of the class or using constants and service structures.
Issue:
The main purpose of static fields is to provide data for all objects of the class or to implement a single point of access. However, improper use of static can lead to elusive bugs related to global state, data races, and testing issues.
Solution:
Static fields are declared using the static keyword:
public class Counter { public static int globalCount = 0; public Counter() { globalCount++; } }
Every time an instance is created, the counter increases, and the value is available through Counter.globalCount, regardless of the object.
Key features:
Can you access a static field through an object instead of the class name?
Yes, the syntax allows accessing a static field through an object, but this leads to unreadable and sometimes confusing code. It is better to always access it through the class name.
Counter c = new Counter(); System.out.println(c.globalCount); // Works, but not recommended
Can static fields be private?
Yes, the access level is not restricted. Private static fields are often used together with public static methods (for example, for Singleton):
public class Singleton { private static Singleton instance; public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } }
What happens when trying to initialize a static field with a value that depends on a non-static field?
Such code will not compile because non-static fields are initialized after static ones. A static field cannot directly reference a non-static one.
In large applications, a static field is used to store cached data specific to a user.
Pros:
Cons:
Using public static final String for storing constants (for example, error codes or standard parameters).
Pros:
Cons: