Q. Constructor or not constructor? Please explain why the output of the following code is null?
public class My {
String s;
public void My(){
s = "Constructor";
}
public void go() {
System.out.println(s);
}
public static void main(String args[]) {
My m = new My();
m.go();
}
}
//output : null
A:
public void My() is not a constructor. The default constructor is called. s is still null by default.
Constructor is not supposed to have a return type, even a void type. If it has, then it is not a constructor, but a method which happens to have the same name as the class name. This is a tricky question just for testing your Java knowledge. Using class name as your method name is not considered as good code practice at work!
Constructor or not constructor?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
static 和 interface的關係
static 和 interface的關係:1)內部接口是隱式的靜態的,不管你是不是用static來修飾注意:內部接口很少用到2)外部接口不能是靜態的
happyzhm5
2020-06-25 22:36:57
初始化順序(Thinking in Java中的一段有意思的例子)
abstract class Glyph { abstract void draw(); Glyph() { System.out.prin
happyzhm5
2020-06-25 22:36:57
Can inner class extends outer class, or opposite?
happyzhm5
2020-02-25 15:57:58
if the reference of the thread is set to null.
happyzhm5
2020-02-25 15:57:58
In what situation, an IllegalThreadStateException will be thrown?
happyzhm5
2020-02-25 15:57:58
Why this code compile OK, but throw ClassCastException at run time?
happyzhm5
2020-02-25 15:57:58
Can one object access a private variable?
happyzhm5
2020-02-25 15:57:58
abstract method Graphics.drawString()?
happyzhm5
2020-02-25 15:57:58
關於線程同步的一點心得
happyzhm5
2018-08-31 04:31:24
left-to-right evaluation rule and side effect
happyzhm5
2018-08-31 04:31:22
Java同步機制淺談――synchronized對代碼作何影響?
happyzhm5
2018-08-31 04:31:20
丟失的違例(小心你的finally)
happyzhm5
2018-08-31 04:31:20
24小時熱門文章