Javaの継承
Javaの継承(サブクラスとスーパークラス)
Javaでは、あるクラスから別のクラスに属性とメソッドを継承することができます。「継承の概念」は次の2つのカテゴリに分類されます。
- サブクラス(子)-別のクラスから継承するクラス
- スーパークラス(親)-継承されるクラス
クラスから継承するには、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);
}
}
protected
Vehicleの修飾子に気づきましたか?
Vehicleのbrand属性をアクセス修飾子に設定します。に設定されている場合、Carクラスはそれにアクセスできません。protected
private
「継承」を使用する理由と時期
-コードの再利用に役立ちます。新しいクラスを作成するときに、既存のクラスの属性とメソッドを再利用します。
ヒント:継承されたメソッドを使用してさまざまなタスクを実行する次の章、ポリモーフィズムも参照してください。
最後のキーワード
他のクラスをクラスから継承させたくない場合は、次のfinal
キーワードを使用します。
クラスにアクセスしようとするとfinal
、Javaはエラーを生成します。
final class Vehicle {
...
}
class Car extends Vehicle {
...
}
出力は次のようになります。
Main.java:9: error: cannot inherit from final Vehicle
class Main extends
Vehicle {
^
1 error)