SCJP 1.6版考題 150
出自 陳富國維基館
Given:
5. import java.io.*;
6. public class Talk{
7. public static void main(String[] args){
8. Console c = new Console();
9. String pw;
10. System.out.print("password: ");
11. pw = c.readLine();
12. System.out.println("got" + pw);
13. }
14.}
If the user types the password aiko when prompted, what is the result?
A. password:
got
B. password:
got aiko
C. password: aiko
got aiko
D. An exception is thrown at runtime.
E. Compilation fails due to an error on line 8.
解答
Ans: E
解說:
系統的Console只有一個,java.io.Console是一個Singleton樣板,不能讓使用者用new的方式來建立多個的Console… 要操作系統的Console要用System.console()取得目前系統的Console
第8行 錯誤的原因是Console的建構子是設為私有的(Singleton的特徵),不能被外界類別叫用,
也就是禁止外界叫用Console建構子來建立Console 物件。要改為:
Console c = System.console();
| ||||||||||||||||||||