SCJP 1.6版考題 105

出自 陳富國維基館
於 2013年3月30日 (六) 05:37 由 Ikk (對話 | 貢獻) 所做的修訂 (新頁面: Given: 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:
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. }

 
And given this code from Class B:
25. A a1 = new A();
26. A a2 = new A();
27. A a3 = new A();
28. System.out.println(A.getInstanceCount());


What is the result?
  A. Compilation of class A fails.
  B. Line 28 prints the value 3 to System.out.
  C. Line 28 prints the value 1 to System.out.
  D. A runtime error occurs when line 25 executes.
  E. Compilation fails because of an error on line 28.

解答


Ans: A

解說:

getInstanceCount是類別A的類別成員方法,在類別方法中要存取非類別成員counter,即物件成員,
先要建立物件或以一個明確的物件參考存取counter物件變數
第6行須改為return new A().counter;