Constructor or not constructor?

来源:互联网 发布:网易云音乐 网络歌曲 编辑:程序博客网 时间:2024/05/21 16:45
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!
原创粉丝点击