Bird
0
0

You want to count how many times a method is called across all objects of a class. Which approach is best?

hard📝 Application Q15 of 15
Java - Static Keyword
You want to count how many times a method is called across all objects of a class. Which approach is best?
AUse a static variable incremented inside the method
BUse an instance variable incremented inside the method
CCreate a new object each time and count in constructor
DUse a local variable inside the method to count calls
Step-by-Step Solution
Solution:
  1. Step 1: Understand counting across all objects

    To count calls across all objects, the counter must be shared by all instances, so it must be static.
  2. Step 2: Evaluate other options

    Instance variables count per object, local variables reset each call, and creating new objects won't track method calls properly.
  3. Final Answer:

    Use a static variable incremented inside the method -> Option A
  4. Quick Check:

    Shared counter needs static variable = C [OK]
Quick Trick: Use static variable to share count across all objects [OK]
Common Mistakes:
  • Using instance variable which counts per object only
  • Using local variable which resets every call
  • Counting in constructor unrelated to method calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes