Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can anyone explain to me why this works the way it does. The output comes out to "Print This". But how does the base class call bar(), when there is no implementation.

abstract class Base
{
    protected virtual void foo()
    {
        bar();
    }

    protected abstract void bar();
}

class Sub : Program
{
    protected override void foo()
    {
        base.foo();
    }

    protected override void bar()
    {
        Console.WriteLine("Print This");
    }

    static void Main(string[] args)
    {
        Sub obj = new Sub();

        obj.foo();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
378 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's the whole point of an abstract class: that it will only ever exist concretely as an instance of the derived class(es). By declaring abstract methods or properties, it is simply forcing the derived class(es) to provide concrete implementations of those members. In this way, if you have an instance of type Base, you can call myInstance.bar and you know that the derived class has implemented it because it wouldn't compile otherwise.

By the way, use pascal case when naming methods, i.e. Foo and Bar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...