class Mystery {
String s;
public static void main(String args[]){
Mystery m = new Mystery();
m.go();
}
void Mystery() {
s = "Constructor";
}
void go() {
System.out.println(s);
}
}
答案:
a. The code compiles and throws an exception at run time.
b. The code runs, but nothing appears in the standard output.
c. The code runs, and “constructor” appears in the standard output.
d. The code runs and writes “null” in the standard output.
初看题目很自然的选择了c,这道题的正确答案为d。输出的是null。java中规定构造函数不能有返回值。所以void Mystery()为一个普通的函数,不是构造函数,s也就没有初始化,故输出null。