Java 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);
}
}
定义和用法
extends
关键字用于扩展一个类(表示一个类继承自另一个类)。
在 Java 中,可以将一个类的属性和方法继承给另一个类。我们将“继承”概念分为两类
- subclass(子类) - 继承自另一个类的类
- superclass(超类) - 被继承的类
要从一个类继承,请使用 extends
关键字。
相关页面
在我们的Java 继承教程中了解更多关于继承的信息。