Junior
What are static variables?
sobes.tech AI
Answer from AI
Static variables belong to the class, not to a specific instance. They exist as a single instance throughout the entire runtime of the program and are shared among all objects of that class. Changing a static variable by one object will be visible to other objects.
Main characteristics:
- Belonging: To the class.
- Number of instances: One per class.
- Lifetime: From the moment the class is loaded until the program terminates.
- Access: Usually by the class name
ClassName.staticVariable, although access through an instance is also possible (not recommended). - Initialization: Once when the class is loaded.
Examples of usage:
- Counters of created class objects.
- Constants shared across the entire class.
- Shared resources managed by the class.
Example in Java:
class MyClass {
static int counter = 0; // Static variable
public MyClass() {
counter++; // Increment static counter upon object creation
}
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println(MyClass.counter); // Output: 2
}
}
Example in Python:
class MyClass:
counter = 0 # Static variable
def __init__(self):
MyClass.counter += 1 # Increment static counter
def main():
obj1 = MyClass()
obj2 = MyClass()
print(MyClass.counter) # Output: 2
if __name__ == "__main__":
main()