Question presented to candidate: "If you have a class with a static counter property that increments in the constructor every time a new instance is created, and you create 3 instances, what does the counter equal — and can you access that counter from one of the instances directly?"
What a strong answer should cover:
- 📌 Interview term:
static— a class member (method or property) prefixed withstaticbelongs to the class itself, not to any individual instance — there is genuinely only ONE copy, shared across every instance, not a separate copy per instance. - 📌 Interview term: the real, direct answer to the prompt — verified directly: a static
countproperty genuinely incremented to3after 3 real instantiations, since every instance's constructor updated the SAME single static value — and that static property is genuinely not accessible directly on an instance (instance.incrementisundefined), only on the class itself (Counter.increment). - 📌 Interview term: static initialization blocks (ES2022) — verified directly: a
static { ... }block genuinely runs once, at class-definition time, useful for static properties needing more complex setup logic than a single expression can provide. - 📌 Interview term: static inheritance — verified directly: a subclass genuinely inherits its parent's static methods — calling a static method on the SUBCLASS that was only defined on the parent genuinely works.
- A precise answer names the real, common use cases for static members: factory methods (
ClassName.create(...)), utility/helper methods that don't need any specific instance's state, and shared counters/registries tracking something across every instance — exactly the pattern verified in this answer's own counter example.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering the prompt's exact scenario (the shared count, and instance-inaccessibility) is the strong signal.
Code / implementation expected: Yes — reproducing the prompt's exact counter scenario, plus verifying instance-inaccessibility, is the clearest, most convincing demonstration.