文章目录
Java 继承(子类和超类)
在 Java 中,可以将属性和方法从一个类继承到另一个类。我们将继承概念分为两类:
- ubclass (child) - 从另一个类继承的类
- subclass (child) - 继承自的类
要从类继承,使用extends 关键字。在下面的例子中,Car类(子类)继承了Vehicle类(超类)的属性和方法:
class Vehicle { protected String brand = "Ford"; public void honk() { System.out.println("Tuut, tuut!"); } } class Car extends Vehicle { private String modelName = "Mustang"; public static void main(String[] args) { Car myFastCar = new Car(); myFastCar.honk(); System.out.println(myFastCar.brand + " " + myFastCar.modelName); } }
运行:
final关键字
如果你不希望其他类继承自一个类,请使用final关键字。
final class Vehicle { protected String brand = "Ford"; public void honk() { System.out.println("Tuut, tuut!"); } } class Main extends Vehicle { private String modelName = "Mustang"; public static void main(String[] args) { Main myFastCar = new Main(); myFastCar.honk(); System.out.println(myFastCar.brand + " " + myFastCar.modelName); } }
如果你尝试访问一个final类,Java 会产生一个错误:
Main.java:9: cannot inherit from final Vehicle class Main extends Vehicle { ^ 1 error