Junior — Middle
What is the purpose and how does the static keyword work in programming languages?
sobes.tech AI
Answer from AI
In Java, the keyword static is used to indicate that a class member (variable or method) belongs to the class itself rather than to any specific instance of the class.
Main features of static:
- Static variables (fields): shared among all instances of the class, exist in a single copy.
- Static methods: can be called without creating an instance of the class, do not have access to non-static fields and methods.
- Static initialization blocks: executed when the class is loaded.
Example:
public class Counter {
private static int count = 0;
public Counter() {
count++;
}
public static int getCount() {
return count;
}
}
// Usage:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // Will output 2
Thus, static allows creating data and methods shared among all objects related to the class, not tied to a specific instance.