@[TOC](继承 (extends) vs 接口实现 (implements))
| 特性 | 继承 (extends) | 接口实现 (implements) |
|---|---|---|
| 数量限制 | 只能继承一个类(单继承) | 可以实现多个接口(多实现) |
| 成员类型 | 继承具体实现 | 实现抽象规范 |
| 构造方法 | 涉及构造方法链(子类必须调用父类构造方法) | 不涉及构造方法(接口没有构造方法) |
| 设计目的 | 代码复用和层次关系 | 定义行为和规范 |
构造方法链(Constructor Chaining)
在继承关系中,子类的构造方法会隐式或显式调用父类的构造方法(通过 super()),形成一条构造方法的调用链。
隐式调用
如果子类构造方法没有显式调用 super(),Java 会自动调用父类的无参构造方法。
class Parent {
Parent() {
System.out.println("Parent 构造方法");
}
}
class Child extends Parent {
Child() {
// 这里隐式调用了 super();
System.out.println("Child 构造方法");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
// 输出
// Parent 构造方法
// Child 构造方法
}
}
显式调用
如果父类没有无参构造方法,子类必须显式调用 super(参数) 来匹配父类的某个构造方法。
- super()必须是子类构造方法中的第一条语句
- 如果父类没有无参构造方法(只有有参构造方法),必须显式调用 super(参数)
- 如果既不写 super()也不写 this()(调用本类其他构造方法),编译器会自动插入 super()
- 在一个构造方法中,要么显式调用 super(),要么显式调用 this(),要么都不写(此时编译器会自动插入 super())。
- 不能同时调用 super()和 this(),因为它们都必须是构造方法的第一条语句。
class Parent {
Parent(int x) { // 只有有参构造方法
System.out.println("Parent 构造方法 with " + x);
}
}
class Child extends Parent {
Child() {
super(10); // 必须显式调用,因为父类没有无参构造方法
System.out.println("Child 构造方法");
}
}
class Parent {
Parent() {
System.out.println("Parent 构造方法");
}
}
class Child extends Parent {
Child() {
this(10); // 调用本类的另一个构造方法 Child(int x)
System.out.println("Child 无参构造方法");
}
Child(int x) {
// 这里隐式调用了 super();
System.out.println("Child 有参构造方法,x = " + x);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
1450

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



