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

Lớp cơ sở (Base Class) trong C#

Khi tạo lớp, thay vì viết mới hoàn toàn, có thể kế thừa thành viên từ lớp hiện có. Lớp hiện có gọi là base class (lớp cơ sở), lớp mới là derived class (lớp dẫn xuất).

Một lớp có thể dẫn xuất từ nhiều lớp/interface (kế thừa đa trọng qua interface).

Cú pháp:

<access-specifier> class <base_class> { ... }
class <derived_class> : <base_class> { ... }

Ví dụ

using System;

namespace InheritanceApplication {
    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 RectangleTester {
        static void Main(string[] args) {
            Rectangle Rect = new Rectangle();
            Rect.setWidth(5);
            Rect.setHeight(7);
            Console.WriteLine("Total area: {0}", Rect.getArea());
            Console.ReadKey();
        }
    }
}