Multiple choice technology programming languages

Click the Exhibit button. 1. public class A { 2. 3. private int counter = 0; 4. 5. public static int getInstanceCount() { 6. return counter; 7. } 8. 9. public A() { 10. counter++; 11. } 12. 13. } Given this code from Class B: 25.A a1 =new A(); 26. A a2 =new A(); 27. A a3 =new A(); 28. System.out.printIn(A.getInstanceCount() ); What is the result?

  1. Compilation of class A fails

  2. Line 28 prints the value 3 to System.out

  3. Line 28 prints the value 1 to System.out.

  4. A runtime error occurs when line 25 executes

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

Static methods cannot directly access instance variables or instance methods because they belong to the class, not to a specific object instance. The method getInstanceCount() is static but tries to access the instance variable counter, causing a compilation failure.

AI explanation

Compilation of class A fails is correct. Line 5 declares getInstanceCount() as static, but it references 'counter' (declared on line 3 as a non-static instance field) directly — a static method cannot access an instance variable without an instance reference. This produces a compile-time error: 'non-static variable counter cannot be referenced from a static context.' Since class A itself doesn't compile, none of the runtime behaviors described in the other options (printing 3, printing 1, or a runtime error at line 25) can occur — the program never even reaches execution.