继承限制
概述
本节介绍 Java 继承的限制。
基本概念
继承限制
| 限制 | 说明 |
|---|---|
| 单继承 | 类只能继承一个父类 |
| 私有成员 | 不能继承私有成员 |
| 构造方法 | 不能继承构造方法 |
代码示例
单继承限制
java
public class SingleInheritanceLimitDemo {
static class A {
void methodA() {}
}
static class B {
void methodB() {}
}
// ❌ 错误:Java 不支持多继承
// class C extends A, B {}
// ✅ 可以通过接口实现多继承
interface InterfaceA { void methodA(); }
interface InterfaceB { void methodB(); }
static class C implements InterfaceA, InterfaceB {
@Override
public void methodA() {}
@Override
public void methodB() {}
}
}私有成员
java
public class PrivateMemberLimitDemo {
static class Parent {
private String privateField = "private";
public String publicField = "public";
private void privateMethod() {
System.out.println("private method");
}
public void publicMethod() {
System.out.println("public method");
}
}
static class Child extends Parent {
public void accessParent() {
// ❌ 不能访问 private 成员
// System.out.println(privateField);
System.out.println(publicField);
// ❌ 不能调用 private 方法
// privateMethod();
// ✅ 可以调用 public 方法
publicMethod();
}
}
}构造方法限制
java
public class ConstructorLimitDemo {
static class Parent {
private String name;
// 构造方法不能被继承
public Parent(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
static class Child extends Parent {
private int age;
// 必须调用父类构造方法
public Child(String name, int age) {
super(name); // 调用父类构造
this.age = age;
}
}
public static void main(String[] args) {
Child child = new Child("张三", 25);
System.out.println(child.getName());
}
}注意事项
- 单继承优点:简单、安全
- 接口弥补:通过接口实现多继承
- 构造调用:子类构造必须调用父类构造
