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

Inheritance

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

Inheritance သည် class တစ်ခုက အခြား class တစ်ခုရဲ့ behavior တွေကို အမွေဆက်ခံတာပါ။ Shared behavior ကို parent class ထဲမှာထားပြီး child class တွေက ထပ်တိုး behavior ထည့်နိုင်ပါတယ်။

ruby
class Vehicle
  def start_engine
    puts "Engine started!"
  end
end

class Car < Vehicle
  def drive
    puts "Driving..."
  end
end

my_car = Car.new
my_car.start_engine
my_car.drive

Car < Vehicle ဆိုတာ Car က Vehicle ကို inherit လုပ်တယ်လို့ဆိုလိုပါတယ်။ ဒါကြောင့် Car object က start_engine ကိုသုံးနိုင်ပါတယ်။

You should see
Engine started! Driving...

Info

Inheritance ကို “is-a” relationship ဖြစ်တဲ့အခါသုံးပါ။ Car is a Vehicle ဆိုတာသဘာဝကျပါတယ်။

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

  • Code reuse အတွက် inheritance ကို အလွန်အကျွံသုံးတာက class hierarchy ရှုပ်စေနိုင်ပါတယ်။ Shared small behavior အတွက် module/mixin ကိုလည်းစဉ်းစားပါ။
Inheritance | Thuta Learning