Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Inheritance

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Inheritance က class တစ်ခုက အခြား class တစ်ခုရဲ့ properties နဲ့ methods တွေကို အမွေဆက်ခံနိုင်တဲ့ feature ပါ။ Common behavior ကို base class ထဲရေးပြီး specific class တွေမှာ ထပ်တိုးနိုင်တာကြောင့် code duplication လျော့စေပါတယ်။

cpp
#include <iostream>
#include <string>
using namespace std;

class User {
  public:
    string name;

    void login() {
        cout << name << " logged in." << endl;
    }
};

class Admin : public User {
  public:
    void deletePost() {
        cout << name << " deleted a post.";
    }
};

int main() {
    Admin admin;
    admin.name = "Thuta Admin";
    admin.login();
    admin.deletePost();
    return 0;
}

Admin : public User ဆိုတာ Admin class က User class ကို public inheritance နဲ့ အမွေဆက်ခံထားတာပါ။ ဒါကြောင့် Admin object က name နဲ့ login() ကို သုံးနိုင်ပြီး deletePost() ကို ထပ်တိုးထားပါတယ်။

You should see
Thuta Admin logged in. Thuta Admin deleted a post.

Info

Inheritance ကို “is-a” relationship ရှိတဲ့အခါ သုံးပါ။ Admin is a User ဆိုရင်သင့်တော်ပါတယ်။ Car has an Engine ဆိုရင် inheritance ထက် composition ပိုသင့်တော်နိုင်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Inheritance ကို code ပြန်သုံးချင်တာတစ်ခုတည်းနဲ့ မသုံးပါနဲ့။ Relationship မမှန်ရင် design ပိုရှုပ်သွားနိုင်ပါတယ်။
Inheritance | Thuta Learning