得知,子类在继承父类时,如果子类中的构造方法未明确调用父类的构造方法,会编译报错,看如下案例。
public class helloWorld {
public static void main(String[] args) {
Student s = new Student("Xiao Ming", 12, 89);
System.out.println(s.name + ":" + s.age + "岁 " + s.score + "分");
}
}
class Person {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
protected int score;
public Student(String name, int age, int score) {
this.score = score;
}
}
然后,预料之内的报错了:
java: 无法将类 Person中的构造器 Person应用到给定类型;
需要: java.lang.String,int
找到: 没有参数
原因: 实际参数列表和形式参数列表长度不同
这是因为,任何class
的构造方法,第一行语句必须是调用父类的构造方法。如果没有明确地调用父类的构造方法,编译器会帮我们自动加一句super();
,所以,Student
类的构造方法实际上是这样:
class Student extends Person {
protected int score;
public Student(String name, int age, int score) {
super(); // 自动调用父类的构造方法
this.score = score;
}
}
但是,Person
类并没有无参数的构造方法,因此,编译失败,并且错误提示依然是:无法将类 Person中的构造器 Person应用到给定类型
解决方法是调用Person
类存在的某个构造方法。例如:
class Student extends Person {
protected int score;
public Student(String name, int age, int score) {
super(name, age); // 调用父类的构造方法Person(String, int)
this.score = score;
}
}
现在就可以正常编译了,编译结果:
Xiao Ming:12岁 89分
因此可以得出结论:如果父类添加了构造方法,并且带有参数,那么子类继承父类时,就必须显示调用 super() 并给出参数,以便能够定位到父类的某个构造方法。如果父类使用默认构造方法且不带任何参数的话,则不需要添加 super()。即子类不会继承任何父类的构造方法。子类默认的构造方法是编译器自动生成的,不是继承的。
©查看原文