Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lớp cơ sở (Base) và lớp dẫn xuất (Derived) trong C#

Một lớp có thể được dẫn xuất từ nhiều lớp hoặc interface, nghĩa là nó có thể kế thừa dữ liệu và hàm từ nhiều base class/interface.

Ví dụ: Base class Vehicle với Derived Classes: Truck, Bus, Motorbike.

Lớp dẫn xuất kế thừa biến thành viên và phương thức của base class.

Ví dụ: Shape và Rectangle

using System;
namespace Program {
    class Shape {
        public void setWidth(int w) { width = w; }
        public void setHeight(int h) { height = h; }
        protected int width;
        protected int height;
    }
    // Derived class
    class Rectangle : Shape {
        public int getArea() { return (width * height); }
    }
    class Demo {
        static void Main(string[] args) {
            Rectangle Rect = new Rectangle();
            Rect.setWidth(5);
            Rect.setHeight(7);
            Console.WriteLine("Diện tích: {0}", Rect.getArea());
            Console.ReadKey();
        }
    }
}

Kết quả

Diện tích: 35