Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การสร้างออบเจกต์ของคลาสที่สืบทอด (Inherited Class) ใน C#

ใน C# คลาสสามารถสืบทอดมาจากคลาสฐาน (Base Class) ได้เพียงคลาสเดียว แต่สามารถทำงานร่วมกับอินเทอร์เฟซหลายตัวได้ คลาสลูก (Derived Class) จะสืบทอดสมาชิกตัวแปรและเมธอดจากคลาสแม่ ทำให้ต้องสร้างออบเจกต์คลาสแม่ก่อนคลาสลูก

ตัวอย่าง: คลาส Tabletop สืบทอดจาก Rectangle

using System;

namespace Demo
{
    class Rectangle
    {
        protected double length;
        protected double width;
        
        public Rectangle(double l, double w)
        {
            length = l;
            width = w;
        }
        
        public double GetArea()
        {
            return length * width;
        }
        
        public void Display()
        {
            Console.WriteLine("ความยาว: {0}", length);
            Console.WriteLine("ความกว้าง: {0}", width);
            Console.WriteLine("พื้นที่: {0}", GetArea());
        }
    }
    
    class Tabletop : Rectangle
    {
        private double cost;
        
        public Tabletop(double l, double w) : base(l, w)
        {
        }
        
        public double GetCost()
        {
            double cost = GetArea() * 70;
            return cost;
        }
        
        public void Display()
        {
            base.Display();
            Console.WriteLine("ค่าใช้จ่าย: {0}", GetCost());
        }
    }
    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Tabletop t = new Tabletop(3, 8);
            t.Display();
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

ความยาว: 3
ความกว้าง: 8
พื้นที่: 24
ค่าใช้จ่าย: 1680

จุดสำคัญ

  • ใช้ : base(l, w) เรียก Constructor ของคลาสแม่
  • คีย์เวิร์ด protected อนุญาตให้คลาสลูกเข้าถึงสมาชิกได้
  • เมธอด Display() ในคลาสลูกใช้ base.Display() เรียกเมธอดของคลาสแม่ก่อน แล้วค่อยเพิ่มข้อมูลของตัวเอง