Senior
How would you answer the question: what can be done to make data common for all objects of a class?
sobes.tech AI
Answer from AI
To make data shared among all objects of a class in Java, you need to use static fields.
A static field belongs to the class itself, not to any specific object, so all instances of the class share the same value of this field.
Example:
public class MyClass {
public static int sharedCounter = 0;
public void increment() {
sharedCounter++;
}
}
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.increment();
System.out.println(MyClass.sharedCounter); // Will output 1
obj2.increment();
System.out.println(MyClass.sharedCounter); // Will output 2
Thus, to have data shared among all objects, declare them as static."}]}]}