Virtual and Abstract method

Ta đã biết các từ khóa Virtual hoặc Abstract (bên lớp cơ sở) và Override (trên lớp dẫn xuất) hỗ trợ tạo đa hình (Polymorphism) cho các phương thức (Method) của object. Phương thức của lớp Cha (lớp cơ sở / base class) sử dụng với từ khóa Virtual hoặc Abstract, tạo phương thức cùng tên ở lớp Con (lớp kế thừa/dẫn xuất / derived class) với Override. Vậy là ta đã có 1 Method đa hình. Vậy khi nào sử dụng Virtual, khi nào dùng Abstract ở lớp cơ sở (lớp Cha) ?

Abstract  method là phương thức chỉ có tên ở lớp cơ sở (base class) và nó phải được cài đặt lại ở tất các các lớp kế thừa (derived class).

abstract class NhanVien
{
    public string HoTen { get; set; }
    public int NamSinh { get; set; }

    public abstract double TinhLuong();

    public virtual void Nhap()
    {
        //Code here
    }
    .......
}

class NhanVienPhongThiNghiem : NhanVien
{
    public double LuongTrongThang { get; set; }

    public override double TinhLuong()
    {
        //Code here
        return LuongTrongThang;
    }

    public override void Nhap()
    {
        base.Nhap();
        //Code here
    }

    public override void Xuat()
    {
        base.Xuat();
        //Code here
    }
}

1. Virtual cho phép lớp Con không nhất thiết phải tạo Override cho method Virtual ở lớp Cha. Ngược lại Abstract thì bắt buộc.

public abstract class Parent
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

2. Cách khai báo, method Virtual có các hàm bên trong còn Abstract thì tuyệt dối không.

public virtual void VirtualMethod() { //code here }
public abstract void AbstractMethod();

3. Method Abstract phải nằm trong class Abstract như bên dưới.

public abstract class Parent
{
    public abstract void AbstractMethod();
}

***Tổng quát:

public abstract class Parent
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class Child : Parent
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // Để gọi các phương thức của lớp cơ sở  
        // C# cho phép ta dùng từ khoá base để gọi đến các phương thức 
        // của lớp cơ sở hiện hành.
        base.VirtualMethod();

        // You are allowed to override this method.
    }
}

Advertisement

Chia sẻ:

Thích bài này:

Thích

Đang tải…