• To invoke a parent constructor, you must place a call to super in the first line of the constructor.
• You can call a specific parent constructor by the arguments that you use in the call to super.
• If no this or super call is used in a constructor, then the compiler adds an implicit call to super() that calls the parent no argument constructor (which could be the default constructor).
If the parent class defines constructors, but does not provide a no-argument constructor, then a compiler error message is issued.
Now you can see what happened here.
• You can call a specific parent constructor by the arguments that you use in the call to super.
• If no this or super call is used in a constructor, then the compiler adds an implicit call to super() that calls the parent no argument constructor (which could be the default constructor).
If the parent class defines constructors, but does not provide a no-argument constructor, then a compiler error message is issued.
Supposed that there is a super class called Employee
For example:
public class Manager extends Employee {
private String department;
public Manager(String name, double salary, String dept) {
super(name, salary);
department = dept;
}
public Manager(String name, String dept) {
super(name);
department = dept;
}
public Manager(String dept) { // This code fails: no super()
department = dept;
}
//more Manager code...
}
Now you can see what happened here.
本文详细解析了Java中使用super关键字调用父类构造器的机制,包括默认构造器的调用规则及如何显式调用特定参数的父类构造器。通过实例演示,帮助开发者理解构造器调用的细节。


被折叠的 条评论
为什么被折叠?



