Java ขยายคำหลัก
ตัวอย่าง
คลาส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 เป็นไปได้ที่จะสืบทอดแอตทริบิวต์และเมธอดจากคลาสหนึ่งไปยังอีกคลาสหนึ่ง เราจัดกลุ่ม "แนวคิดการสืบทอด" ออกเป็นสองประเภท:
- คลาสย่อย (ลูก) - คลาสที่สืบทอดมาจากคลาสอื่น
- superclass (parent) - คลาสที่สืบทอดมาจาก
หากต้องการสืบทอดจากคลาส ให้ใช้extends
คีย์เวิร์ด
หน้าที่เกี่ยวข้อง
อ่านเพิ่มเติมเกี่ยวกับการสืบทอดใน บทช่วย สอนการสืบทอด Javaของ เรา