Because the parent class defines a constructor that has parameters, the compiler does not call the default parameterless constructor. When a subclass inherits, the constructor of the parent class must be explicitly called in its own constructor to ensure that the parent class is instantiated before the child class is initialized. If you have a constructor in your parent class that does not have a parameter, the subclass will not force the call, and the compiler will help you invoke the constructor of the parent class by default. Parent class
class Person {
protected String name;
protected int age;
//你已经定义了自己的构造函数,此时编译器不会为你创建默认的构造函数
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public void print() {
System.out.println("Name:"+name+"/nAge:"+age);
}
}
Sub-class
class Student extends Person {
public Student(){ //子类构造函数
//super(); 不行,因为你的父类没有无参的构造函数
super("a",1);
//显示调用父类的构造函数,而且必须是第一行调用
}
}
class Test {
public static void main(String args[]){
}
}
Implicit Super constructor XX () is undefined for default constructor