Java rozszerza słowo kluczowe
Przykład
Klasa Car
(podklasa) dziedziczy atrybuty i metody z Vehicle
klasy (superklasa):
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);
}
}
Definicja i użycie
Słowo extends
kluczowe rozszerza klasę (wskazuje, że klasa jest dziedziczona z innej klasy).
W Javie możliwe jest dziedziczenie atrybutów i metod z jednej klasy do drugiej. Grupujemy „koncepcję dziedziczenia” na dwie kategorie:
- subclass (child) - klasa, która dziedziczy z innej klasy
- superclass (parent) - klasa, z której jest dziedziczona
Aby dziedziczyć z klasy, użyj extends
słowa kluczowego.
Powiązane strony
Przeczytaj więcej o dziedziczeniu w naszym samouczku dotyczącym dziedziczenia w języku Java .