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 個錯誤)