Constructor or not constructor?

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!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章