Java mở rộng từ khóa
Ví dụ
Lớp Car
(subclass) kế thừa các thuộc tính và phương thức từ lớp Vehicle
(siêu lớp):
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); } }
Định nghĩa và cách sử dụng
Từ khóa extends
mở rộng một lớp (chỉ ra rằng một lớp được kế thừa từ một lớp khác).
Trong Java, có thể kế thừa các thuộc tính và phương thức từ lớp này sang lớp khác. Chúng tôi nhóm "khái niệm thừa kế" thành hai loại:
- lớp con (con) - lớp kế thừa từ lớp khác
- superclass (cha mẹ) - lớp được kế thừa từ
Để kế thừa từ một lớp, hãy sử dụng từ khóa extends
.
Trang liên quan
Đọc thêm về kế thừa trong Hướng dẫn kế thừa Java của chúng tôi.