Sobes.tech
Junior — Middle

Mis vahe on staatilise muutujaga programmeerimises ja millised on selle omadused?

sobes.tech AI

Vastus AI-lt

A static variable is a variable that belongs to the class, not to a specific instance of an object. It exists in a single instance for the entire class and retains its value between method calls.

Features of static variables:

  • Shared among all instances of the class: all objects of the class share the same static variable.
  • Initialized once when the class is loaded.
  • Accessible without creating an instance of the class (via the class name).
  • Used to store state or data common to all objects.

Example in Java:

public class Counter {
    public static int count = 0;

    public Counter() {
        count++;
    }
}

// Usage:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count); // Will print 2

In testing, static variables can cause difficulties because their state persists between tests, which can lead to unwanted side effects. Therefore, it is important to clear or isolate static data in tests.