关于构造函数
class human{int age;
human(){
age=1;
System.out.println("Human");
}
}
class boy extends human{
boy(){
System.out.println("boy");
}
}
public class test{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
human h=new human();
System.out.println(h.age);
boy b=new boy();
}
}
如果将构造函数human()和boy()定义为void human()和void boy()。则构造函数不会运行,这是什么原因? 构造函数是不能有返回值的
即使是void也不行
这是语言的规定 构造函数必须和类名同名,且没有返回值,否则编译器就不能晓得这个函数是构造函数了,添加void 相当于重新声明了成员函数,这个时候不是构造函数没有运行,而是执行了默认的构造函数;
页:
[1]