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 繼承教程中瞭解更多關於繼承的資訊。