代码:
1.父类中没有无参的构造方法。
class Person {
String name = "No name";
public Person(String nm) {
name = nm;
}
}
class Employee extends Person {
String empID = "0000";
public Employee(String id) {
empID = id;
}
}
public class Test {
public static void main(String args[]) {
Employee e = new Employee("123");
System.out.println(e.empID);
}
}
结果:
Implicit super constructor Person() is undefined. Must explicitly invoke another constructor
编译不能通过
解释:
1.子类在new一个实例的时候,如果子类的构造方法没有显式调用父类构造方法,则默认调用无参数的构造方法。
2.当父类没有无参的构造方法时,需要显示的调用父类的构造方法
class Employee extends Person {
String empID = "0000";
public Employee(String id) {
super("123");//需要显示调用
empID = id;
}
}<strong><em></em><u></u><sub></sub><sup></sup><del></del>
</strong>