學習C#--抽象類

該類不能夠被實例化,可是定義了子類必須覆蓋的類成員函數。ide

使用時,要注意abstract和virtual成員函數的區別:函數

1. virtual函數能夠被overwrite也能夠不覆蓋,該函數具備實際的定義功能。this

abstract class FourLeggedAnimal
    {
        public virtual string Describe()
        {
            return "Not much is known about this four legged animal!";
        }
    }

class Dog : FourLeggedAnimal
    {

    }

或者code

abstract class FourLeggedAnimal
{
    public virtual string Describe()
    {
        return "This animal has four legs.";
    }
}


class Dog : FourLeggedAnimal
{
    public override string Describe()
    {
        string result = base.Describe();
        result += " In fact, it's a dog!";
        return result;
    }
}

2. abstract函數只是定義了函數接口,沒有實際功能,必須在待實例化的子類中從新實現。接口

abstract class FourLeggedAnimal
    {
        public abstract string Describe();
    }


class Dog : FourLeggedAnimal
    {

        public override string Describe()
        {
            return "I'm a dog!";
        }
    }

class Cat : FourLeggedAnimal
    {
        public override string Describe()
        {
            return "I'm a cat!";
        }
    }
相關文章
相關標籤/搜索