Inheritance (การสืบทอด)เป็นคุณสมบัติในการเขียนโปรแกรมเชิงวัตถุ โดยคลาสใหม่สามารถสืบทอดคุณสมบัติและ Method ของคลาสที่มีอยู่จากคลาสแม่ (Parent) ที่เรียกว่า base class นอกจากนี้ยังสามารถเพิ่มคุณสมบัติและ Method ใหม่ๆของคลาสตัวเองได้ คลาสที่รับการสืบทอดมานั้นเรียกว่าคลาสลูก (delivered class or child) การสืบทอดคือการนำคุณสมบัติต่างๆในคลาสหลักมาใช้ซ้ำ ทำให้มีการปรับเปลี่ยน หรือ บำรุงรักษา Code ที่ง่าย และมีการดู Code จัดระเบียบได้ง่ายขึ้น และ การเรียกใช้ Consturctor ของ Parent Class ใน C# จะใช้ Funtion base()
ประเภทของการสิบทอด
การสืบทอด ( inheritance ) นั้นมี 5 ประเภทดังนี้
Single inheritance
เป็นการสิบทอดแบบ 1 base class และ 1 delivered class จากรูป B สิบทอดคุณสมบัติจาก A
Multilevel inheritance
เป็นการสิบทอดจาก base class มาเป็นทอดๆไปเรื่อยๆโดยตอนแรกเริ่มต้นจากคลาสลูก B สิบทอดคุณสมบัติของ base class A มาและคลาส C สืบทอดคุณสมบัติต่อจากคลาส B อีกทีนึง เรียกว่าการสิบทอดหลายระดับ ดังรูป
Hierarchical inheritance
เป็นการสิบทอดที่มี base class เพียง 1 class และ chlid class หลาย class ที่สืบทอดคุณสมบัติมาจาก base class เช่น คลาส B and C สืบทอดคุณสมบัติจาก A ดังรูป
Multiple inheritance
เป็นการสิบทอดที่คลาสลูกคลาส 1 ศามารถมีคลาสแม่ได้มากกว่า 1 class และสามารถสืบทอดคุณสมบัติจาก class ทั้งหมดมาได้ แต่เนื่องจากใน C# นั้น ไม่ได้สนับสนุนการใช้ Multiple inheritance แบบโดยตรงเราเลยต้องใช้การ interface มาช่วยในเรื่องนี้ จากรูปนั้น C (child) สิบทอดคุณสมบัติจาก A,B ที่เป็น super class
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.
}
}
using System;
public class Person
{
public string persondet()
{
return "this is the person class";
}
}
public class Bird : Person
{
public string birddet()
{
return "this is the birddet Class";
}
}
public class Animal : Bird
{
public string animaldet()
{
return "this is the Animal Class";
}
}
public class Program
{
public static void Main(string[] args)
{
Animal animal = new Animal();
Console.WriteLine(animal.persondet());
Console.WriteLine(animal.birddet());
Console.WriteLine(animal.animaldet());
}
}
using System;
public class A // base class
{
public string msg()
{
return "this is A class Method";
}
}
public class B : A // B class inherits from A
{
public string info()
{
return msg() + "\nthis is B class Method";
}
}
public class C : A // C class inherits from A
{
public string getinfo()
{
return msg() + "\nthis is C class Method";
}
}
public class Program
{
public static void Main(string[] args)
{
B b = new B();
C c = new C();
Console.WriteLine(b.info());
Console.WriteLine(c.getinfo());
}
}
using System;
public interface IA //ineterface 1
{
string setImgs(string a);
}
public interface IB //Interface 2
{
int getAmount(int Amt);
}
public class ICar : IA, IB //implementatin
{
public int getAmount(int Amt)
{
return 100;
}
public string setImgs(string a)
{
return "this is the car";
}
}
public class Program
{
public static void Main(string[] args)
{
ICar car = new ICar();
string imageResult = car.setImgs("carImage");
int amountResult = car.getAmount(150);
Console.WriteLine(imageResult);
Console.WriteLine("Amount: " + amountResult);
}
}
using System;
interface IShape
{
void Draw();
}
class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
}
// Squre class is inheriting from both Circle class and IShape interface
class Square : Circle, IShape
{
public void Draw()
{
Console.WriteLine("Drawing a square.");
}
}
class Program
{
static void Main(string[] args)
{
Circle circle = new Circle();
circle.Draw(); // Output: Drawing a circle.
Rectangle rectangle = new Rectangle();
rectangle.Draw(); // Output: Drawing a rectangle.
Square square = new Square();
square.Draw(); // Output: Drawing a square.
}
}
Buddy is eating.
Buddy is barking.
this is the person class
this is the birddet Class
this is the Animal Class
this is A class Method
this is B class Method
this is A class Method
this is C class Method
this is the car
Amount: 100
Drawing a circle.
Drawing a rectangle.
Drawing a square.
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
using System;
class A
{
}
class B : A
{
public void M()
{
Console.WriteLine("B");
}
}
class C : B
{
public void M() // I need to use public new void M() to avoid the warning
{
Console.WriteLine("C");
}
}
class D : 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: B-C-C
using System;
class A
{
}
class B : A
{
public virtual void M()
{
Console.WriteLine("B");
}
}
class C : B
{
public override void M() // I need to use public new void M() to avoid the warning
{
Console.WriteLine("C");
}
}
class D : 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;
}
using System;
public interface IA //ineterface 1
{
string setImgs(string a);
}
public interface IB //Interface 2
{
int getAmount(int Amt);
}
public class ICar : IA, IB //Multiple
{
public int getAmount(int Amt)
{
return 100;
}
public string setImgs(string a)
{
return "this is the car";
}
}
public class Program
{
public static void Main(string[] args)
{
ICar car = new ICar();
string imageResult = car.setImgs("carImage");
int amountResult = car.getAmount(150);
Console.WriteLine(imageResult);
Console.WriteLine("Amount: " + amountResult);
}
}
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}")
using System;
public interface IA //ineterface 1
{
string setImgs(string a);
}
public interface IB //Interface 2
{
int getAmount(int Amt);
}
public class ICar : IA, IB //Multiple
{
public int getAmount(int Amt)
{
return 100;
}
public string setImgs(string a)
{
return "this is the car";
}
}
public class Program
{
public static void Main(string[] args)
{
ICar car = new ICar();
string imageResult = car.setImgs("carImage");
int amountResult = car.getAmount(150);
Console.WriteLine(imageResult);
Console.WriteLine("Amount: " + amountResult);
}
}