Junior
What applications is the static modifier suitable for?
sobes.tech AI
Answer from AI
- Class variables (static fields): For storing data common to all instances of the class. For example, a counter of created objects or constants.
- Class methods (static methods): For performing actions that do not depend on a specific instance of the class. For example, helper functions or methods for working with static fields.
- Static initialization blocks: For performing complex initialization of static fields when the class is loaded.
- Nested static classes: For logical grouping of related classes or for use as helper classes without a reference to an external object.
Examples:
public class MyClass {
// Static field (constant)
public static final int MAX_COUNT = 100;
// Static field (instance counter)
private static int instanceCount = 0;
// Static initialization block
static {
System.out.println("MyClass loaded.");
}
public MyClass() {
instanceCount++;
}
// Static method
public static int getInstanceCount() {
return instanceCount;
}
// Nested static class
public static class StaticInnerClass {
public void doSomething() {
System.out.println("In static inner class.");
}
}
}
Comparison table of static and non-static members:
| Attribute | Static member | Non-static member |
|---|---|---|
| Object association | Belongs to the class | Belongs to an instance |
| Access | Via class name or object | Via object |
| Initialization | When the class is loaded | When the object is created |
| Memory | Allocated once | Allocated for each object |