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

Inheritance

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

Inheritance က class တစ်ခုက အခြား class တစ်ခုရဲ့ properties/methods တွေကို အမွေဆက်ခံတဲ့ OOP concept ပါ။ Swift မှာ inheritance ကို class တွေပဲ support လုပ်ပါတယ်။ Struct နဲ့ enum မှာ inheritance မရှိပါ။

Inheritance က shared behavior တွေကို reuse လုပ်ဖို့ကောင်းပေမယ့် မလိုအပ်ဘဲအလွန်အကျွံသုံးရင် code ကိုနားလည်ရခက်စေနိုင်ပါတယ်။ Swift မှာ protocol composition နဲ့ struct ကိုလည်း အများကြီးအသုံးပြုကြပါတယ်။

swift
class Notification {
    func send() {
        print("Sending notification...")
    }
}

class EmailNotification: Notification {
    override func send() {
        print("Sending email notification")
    }
}

let email = EmailNotification()
email.send()

EmailNotification က Notification ကို inherit လုပ်ထားပါတယ်။ Parent class ရဲ့ send() method ကို child class မှာ ကိုယ်ပိုင် behavior နဲ့ပြန်ရေးချင်လို့ override သုံးထားပါတယ်။

You should see
Sending email notification

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

  • Struct ကို inherit လုပ်လို့မရပါ။ Data model အများစုအတွက် struct + protocol ကိုအရင်စဉ်းစားပါ။
Inheritance | Thuta Learning