Java 继承
Java 继承(子类和超类)
在 Java 中,一个类可以继承另一个类的属性和方法。我们将“继承概念”分为两类:
- subclass(子类) - 继承自另一个类的类
- superclass(超类) - 被继承的类
要从一个类继承,请使用 extends
关键字。
在下面的示例中,Car
类(子类)继承了 Vehicle
类(超类)的属性和方法
示例
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
您注意到 Vehicle 中的 protected
修饰符了吗?
我们将 Vehicle 中的 brand 属性设置为 protected
访问修饰符。如果它被设置为 private
,Car 类将无法访问它。
为何以及何时使用“继承”?
- 这对于代码重用很有用:当您创建新类时,可以重用现有类的属性和方法。
提示: 也请看一下下一章,多态,它使用继承的方法来执行不同的任务。
final 关键字
如果您不希望其他类从某个类继承,请使用 final
关键字
如果您尝试访问一个 final
类,Java 将会产生一个错误
final class Vehicle {
...
}
class Car extends Vehicle {
...
}
输出可能类似于:
Main.java:9: error: cannot inherit from final Vehicle (错误:无法从 final Vehicle 继承)
class Main extends Vehicle {
^
1 个错误)