Bird
0
0

How can you modify this class to count how many objects of Counter have been created?

hard📝 Application Q9 of 15
Java - Object-Oriented Programming Concepts
How can you modify this class to count how many objects of Counter have been created?
class Counter {
  int id;
  Counter(int id) {
    this.id = id;
  }
}
AAdd a static int variable and increment it in the constructor
BAdd an instance int variable and increment it in the constructor
CAdd a static method to return the count without variables
DAdd a local variable in constructor to count objects
Step-by-Step Solution
Solution:
  1. Step 1: Understand counting objects

    To count all objects created, use a static variable shared by all instances.
  2. Step 2: Increment static variable in constructor

    Incrementing the static variable inside the constructor updates count each time an object is created.
  3. Final Answer:

    Add a static int variable and increment it in the constructor -> Option A
  4. Quick Check:

    Static variable tracks all instances [OK]
Quick Trick: Use static variable to count all objects [OK]
Common Mistakes:
  • Using instance variable for counting
  • Using local variables which reset each time

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes