Java အမွေအနှစ်
Java Inheritance (Subclass နှင့် Superclass)
Java တွင်၊ class တစ်ခုမှ အခြားတစ်ခုသို့ attribute များနှင့် method များကို အမွေဆက်ခံနိုင်သည်။ ကျွန်ုပ်တို့သည် "အမွေဆက်ခံခြင်းသဘောတရား" ကို အမျိုးအစားနှစ်မျိုးဖြင့် အုပ်စုဖွဲ့သည်-
- အတန်းခွဲ (ကလေး) - အခြားအတန်းမှ အမွေဆက်ခံသော အတန်း
- superclass (မိဘ) - ထံမှအမွေဆက်ခံခံရသောအတန်း
အတန်းတစ်ခုမှ အမွေဆက်ခံရန် extends
သော့ချက်စကားလုံးကို အသုံးပြုပါ။
အောက်ဖော်ပြပါ ဥပမာတွင်၊ Car
class (subclass) သည် Vehicle
class (superclass) မှ attribute နှင့် method အား အမွေဆက်ခံသည်-
ဥပမာ
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
ယာဉ်ရှိ ပြုပြင်မွမ်းမံမှုကို သတိပြုမိ ပါသလား။
ကျွန်ုပ်တို့သည် မော်တော် ယာဉ် ရှိ အမှတ်တံဆိပ် ရည်ညွှန်း ချက်ကို အသုံးပြုခွင့် မွမ်းမံ မှုအဖြစ် သတ်မှတ်သည် ။ ၎င်းကို သတ်မှတ်ထားပါက ၊ Car class သည် ၎င်းကို ဝင်ရောက်နိုင်မည်မဟုတ်ပေ။protected
private
"အမွေဆက်ခံခြင်း" ကို ဘာကြောင့် အသုံးပြုရသလဲ
- ကုဒ်ပြန်သုံးနိုင်မှုအတွက် အသုံးဝင်သည်- သင်အတန်းသစ်တစ်ခုဖန်တီးသောအခါ ရှိပြီးသား class တစ်ခု၏ အရည်အချင်းများနှင့် နည်းလမ်းများကို ပြန်လည်အသုံးပြုပါ။
အကြံပြုချက်- မတူညီသောအလုပ်များကိုလုပ်ဆောင်ရန် အမွေဆက်ခံသည့်နည်းလမ်းများကိုအသုံးပြုသည့် နောက်အခန်း၊ Polymorphism ကိုလည်းကြည့်ရှုကြည့်ပါ ။
နောက်ဆုံး Keyword ပါ။
အခြားအတန်းများကို အတန်းတစ်ခုမှ အမွေဆက်ခံရန် မလိုလားပါက၊ final
သော့ချက်စကားလုံးကို အသုံးပြုပါ။
အကယ်၍ သင်သည် class တစ်ခုကို ဝင်ရောက်ရန် ကြိုးစားပါက final
၊ Java သည် error ထုတ်ပေးလိမ့်မည်-
final class Vehicle {
...
}
class Car extends Vehicle {
...
}
အထွက်သည် ဤကဲ့သို့သော အရာဖြစ်လိမ့်မည်-
Main.java:9: error: cannot inherit from final Vehicle
class Main extends
Vehicle {
^
1 error)