java 中子类的构造方法一定要调用父类的构造方法吗

请看:
public class Light {
private int watts;
private boolean indicator;
public Light(int watts){
this.watts=watts;
}
public Light(int watts,boolean indicator){
this.watts=watts;
this.indicator=indicator;
}
public void switchOn(){
this.indicator=true;
}
public void switchOff(){
this.indicator=false;
}
public void printInfo(){
System.out.println("watts:"+this.watts+"indicator:"+this.indicator);
}

}
class TubeLight extends Light{
private int tubeLength;
private String color;
private int watts;
private boolean indicator;
public TubeLight(int watts,int tubeLength,String color){
super(watts);
this.watts=watts;
this.color=color;
this.tubeLength=tubeLength;
}
public void printInfo(){
System.out.println("watts:"+this.watts+" indicator:"+this.indicator+" tubeLength:"+this.tubeLength+" color:"+this.color);
}
}

请问在以上的父类Light和子类TubeLight中,为什么子类TubeLight的构造方法public TubeLight(int watts,int tubeLength,String color)一定要调用super(watts),否则报错:
TubeLight.java:6: 找不到符号
符号: 构造函数 Light()
位置: 类 Light
public TubeLight(int watts,int tubeLength,String color){

^
请问如果父类只有有参构造函数,子类是否也无条件调用父类的有参构造函数呢?

不是一定要调用,你只要在Light类中加入一个无参数的构造函数:
public Light(){}
事情就解决了。
因为你在Light类里自己创建了有参构造函数,那么系统不会再自动生成无参的构造函数。
子类会无条件继承父类无参构造函数,而你父类里没有无参构造函数,子类继承时会报错,这个一定要注意。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2007-12-30
不需要显式调用,但是一定会有隐式调用的。

子类没有构造函数的时候会就要求父类必须有无参构造函数。

如果子类有任意一个构造函数(无论有无参数),父类又 没有声明无参构造函数,那么Object类的无参构造函数可能会被调用。

这是实例代码:
public class Father {
public Father() {
System.out.println("Father's constructor.");
}

public static void main(String[] args) {
new Son(2);
}
}

class Son extends Father {
public Son(int age) {
System.out.println("Son's constructor. " + age);
}
}
第2个回答  2007-12-30
java 中子类的构造方法一定要调用父类的构造方法:这个是正确的。
关于:回答者:uuwoxin - 江湖新秀 四级 12-30 00:43
的答案。起去试一下就知道是对是错了。
相似回答