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

Ghi đè phương thức (Overriding) trong C#


Đa hình runtime có ghi đè phương thức, còn gọi là liên kết động (dynamic binding) hoặc liên kết muộn (late binding). Được triển khai bằng lớp trừu tượng (abstract class) và hàm ảo (virtual function). Lớp trừu tượng chứa phương thức trừu tượng, được triển khai bởi lớp dẫn xuất.

Ví dụ về lớp trừu tượng triển khai đa hình runtime và ghi đè:

Ví dụ

using System;
namespace PolymorphismApplication {
    abstract class Shape {
        public abstract int area();
    }
    class Rectangle : Shape {
        private int length;
        private int width;
        public Rectangle(int a = 0, int b = 0) {
            length = a;
            width = b;
        }
        public override int area() {
            Console.WriteLine("Diện tích lớp Rectangle:");
            return (width * length);
        }
    }
    class RectangleTester {
        static void Main(string[] args) {
            Rectangle r = new Rectangle(10, 7);
            double a = r.area();
            Console.WriteLine("Diện tích: {0}", a);
            Console.ReadKey();
        }
    }
}