Inheritance in C#

ศัญฑิวรรณ วงษ์สมบัติ 650710584

Inheritance คือ

Inheritance (การสืบทอด) เป็นคุณสมบัติในการเขียนโปรแกรมเชิงวัตถุ โดยคลาสใหม่สามารถสืบทอดคุณสมบัติและ Method ของคลาสที่มีอยู่จากคลาสแม่ (Parent) ที่เรียกว่า base class นอกจากนี้ยังสามารถเพิ่มคุณสมบัติและ Method ใหม่ๆของคลาสตัวเองได้ คลาสที่รับการสืบทอดมานั้นเรียกว่าคลาสลูก (delivered class or child) การสืบทอดคือการนำคุณสมบัติต่างๆในคลาสหลักมาใช้ซ้ำ ทำให้มีการปรับเปลี่ยน หรือ บำรุงรักษา Code ที่ง่าย และมีการดู Code จัดระเบียบได้ง่ายขึ้น และ การเรียกใช้ Consturctor ของ Parent Class ใน C# จะใช้ Funtion base()

ประเภทของการสิบทอด

การสืบทอด ( inheritance ) นั้นมี 5 ประเภทดังนี้

  1. Single inheritance

    เป็นการสิบทอดแบบ 1 base class และ 1 delivered class จากรูป B สิบทอดคุณสมบัติจาก A

  2. Multilevel inheritance

    เป็นการสิบทอดจาก base class มาเป็นทอดๆไปเรื่อยๆโดยตอนแรกเริ่มต้นจากคลาสลูก B สิบทอดคุณสมบัติของ base class A มาและคลาส C สืบทอดคุณสมบัติต่อจากคลาส B อีกทีนึง เรียกว่าการสิบทอดหลายระดับ ดังรูป

  3. Hierarchical inheritance

    เป็นการสิบทอดที่มี base class เพียง 1 class และ chlid class หลาย class ที่สืบทอดคุณสมบัติมาจาก base class เช่น คลาส B and C สืบทอดคุณสมบัติจาก A ดังรูป

  4. Multiple inheritance

    เป็นการสิบทอดที่คลาสลูกคลาส 1 ศามารถมีคลาสแม่ได้มากกว่า 1 class และสามารถสืบทอดคุณสมบัติจาก class ทั้งหมดมาได้ แต่เนื่องจากใน C# นั้น ไม่ได้สนับสนุนการใช้ Multiple inheritance แบบโดยตรงเราเลยต้องใช้การ interface มาช่วยในเรื่องนี้ จากรูปนั้น C (child) สิบทอดคุณสมบัติจาก A,B ที่เป็น super class

  5. Hybrid inheritance

    เป็นการผสมผสานการสืบทอดกันระหว่าง 2 ประเภทขึ้นไปแต่เนื่องจาก C# ไม่รองรับการสิบทอดแบบผสมผสานเราเลยต้องใช้ interface มาช่วยจัดการเหมือนกับเช่นหัวข้อที่ 4 จการูป B สืบทอดคุณสมบัติจาก A และ C,D สืบทอดคุณสมบัติจาก B อีกที

ในการเขียนโค้ดนั้นรูปแบบของการเขียนจะเป็น class chlid:parent {}

ตัวอย่างโค้ดการสืบทอดแต่ละประเภท

using System;

class Animal
{
    protected string name;

    public Animal(string name)
    {
        this.name = name;
    }

    public void Eat()
    {
        Console.WriteLine($"{name} is eating.");
    }
}

// Derived class
class Dog : Animal
{
    public Dog(string name) : base(name)
    {
    }

    public void Bark()
    {
        Console.WriteLine($"{name} is barking.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating an instance of the derived class
        Dog myDog = new Dog("Buddy");

        // Accessing the inherited method from the base class
        myDog.Eat(); // Output: Buddy is eating.

        // Accessing the method defined in the derived class
        myDog.Bark(); // Output: Buddy is barking.
    }
}

Buddy is eating.
Buddy is barking.

เปรียบเทียบ Inheritance ใน C# กับภาษา Java,C++ และ Python

คุณสมบัติการ Inheritace ระหว่าง 4 ภาษา มีความแตกต่างกันหรือเหมือนกันดังนี้

  • ในภาษา Java นั้นจะมีคุณสมบัติการสิบทอดคล้ายกับ C# มากๆแต่จะมีความแตกต่างในขณะเรียกใช้นิดหน่อยในเรื่องของ virtual funtion ซึ่งจากตัวอย่างโค้ดนี้ ใน ภาษา Java นั้นจะได้ผลลัพธ์เป็น C-C-C ขณะที่ C# ได้ผลลัพธ์เป็น B-C-C ซึ่งดูสมเหตุสมผลมากกว่า ทำไมถึงเป็นอย่างนั้น ? เพราะว่า Java หาก ไม่ได้กำหนดเป็น static method นั้นจะเป็น virtual โดยอัตโนมัติเวลามีการ override ในเมธอดคลาสลูกจากตัวอย่างนี้ การเรียกใช้ก็จะเรียกจากคลาสลูกที่ Override ไปเสมอ ใน C# หากจะทำเหมือน Java จะต้องใช้คำสั่ง Override ในคลาสลูกและใช้ virtual ในคลาสแม่จึงจะเปลี่ยนให้

class A 
{
}
class B extends A
{
    public void m()
    {
        System.out.println("B\n");
    }
}
class C extends B
{
    public void m()
    {
        System.out.println("C\n");
    }
}
class D extends C
{
    public static void main(String[] args)
    {
        A a = new D();
        // a.m(); // doesn't work
        B b = new D();
        b.m();
        C c = new D();
        c.m();
        D d = new D();
        d.m();
    }
}

//Output: C-C-C
  • ในภาษา C++ มีการสืบทอดแต่ละประเภทเหมือนกับ C# แต่ C++ นั้นจะรองรับการสืบทอดแบบ Multiple inheritace ซึ่งใน C# ไม่สามารถทำได้ จากโค้ดตัวอย่างนั้น จะเห็นได้ว่า C# จะใช้คำสั่ง Interface IA and IB ทั้งสองตัวเพื่อจะได้สามารถนำคลาสแม่ทั้งสองคลาสมาให้คลาสลูกสืบทอดคุณสมบัติของ 2 คลาสแม่ได้ ซึ่งใน C++ สามารถใส่คลาสแม่ทั้งสองคลาสเข้าไปได้เลยไม่ต้องทำการสร้าง Interface ให้กับคลาสแม่ ใช้เพียงแค่ virtual funtion และ override เท่านั้น

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

// First interface IA
class IA {
public:
    virtual string setImgs(string a) = 0; // virtual function
};

// Second interface IB
class IB {
public:
    virtual int getAmount(int Amt) = 0; // virtual function
};

// Class ICar implementing both IA and IB
class ICar : public IA, public IB {
public:
    // Implementing setImgs from IA
    string setImgs(string a) override {
        return "this is the car";
    }
    
    // Implementing getAmount from IB
    int getAmount(int Amt) override {
        return 100; // Returns a fixed amount
    }
};

int main() {
    ICar car; // Creating an object of ICar
    string imageResult = car.setImgs("carImage");
    int amountResult = car.getAmount(150);
    
    cout << imageResult << endl; 
    cout << "Amount: " << amountResult << endl; 
    
    return 0;
}
  • ในภาษา Python นั้นมีการรองรับการสืบทอดแบบ Multiple โดยตรงเช่นเดียวกันกับ C++ ซึ่ง C# ไม่มีอีกเช่นเคยและการ override ของ Python นั้นไม่ต้องใช้คำสั่งพิเศษก็สามารถทำได้เลยซึ่งแตกต่างจาก C# จาโค้ดตัวอย่างเดียวกันกับ Multiple ของ C# จะเห็นได้ว่าตรงคลาส ICar มีการใช้ Multiple โดยตรงแบบสามารถใช้ได้ไม่เกิด error โดยไม่ต้องมีการ Interface class แม่

from abc import ABC, abstractmethod

#interface 1
class IA(ABC):
    @abstractmethod
    def set_imgs(self, a: str) -> str:
        pass

#interface 2
class IB(ABC):
    @abstractmethod
    def get_amount(self, amt: int) -> int:
        pass

# Multiple
class ICar(IA, IB):
    def get_amount(self, amt: int) -> int:
        return 100

    def set_imgs(self, a: str) -> str:
        return "this is the car"

if __name__ == "__main__":
    car = ICar()
    image_result = car.set_imgs("carImage")
    amount_result = car.get_amount(150)
    print(image_result)
    print(f"Amount: {amount_result}")

Presentation

Slide

Reference

Inheritance (C#) : https://www.geeksforgeeks.org

type of inheritance : https://www.programiz.com

Example of C# (1,4) : https://www.shekhali.com

Example of C# (2,3,5) : https://www.c-sharpcorner.com

Java : https://www.javatpoint.com

Example of Java & C# : https://stackoverflow.com

C++ : https://www.geeksforgeeks.org

Python : https://www.geeksforgeeks.org

Last updated