简体   繁体   中英

Inherit from a non-abstract class

I have several classes which inherit from a BaseClass which has an abstract method called GetData. In one of them I want to basically inherit from again and provide use a new method called GetArticles which I call from GetData. Here's the code.

public abstract class BaseClass
{
    internal abstract void GetData();
}

internal class FirstClass : BaseClass
{
    internal override void GetData()
    {
        // calls GetArticles
    }

    protected void GetArticles()
    {
    }
}

internal class SecondClass : FirstClass
{
    protected new void GetArticles()
    {
    }
}

GetArticles is never called in SecondClass . It calls the one in FirstClass , even though my object is of type SecondClass . I can't make GetArticles in FirstClass Abstract because I want to use FirstClass in its own right.

Any suggestions?

Your method has to marked as virtual in FirstClass and overriden using override keyword in SecondClass .

internal class FirstClass : BaseClass
{
    internal override void GetData()
    {
        // calls GetArticles
    }

    protected virtual void GetArticles()
    {
    }
}

internal class SecondClass : FirstClass
{
    protected override void GetArticles()
    {
    }
}

new modifier hides the underlying virtual method, which is not what you want. Check Knowing When to Use Override and New Keywords (C# Programming Guide) on MSDN.

Declare GetArticles in your FirstClass as virtual. In the second class remove new and add override

Make GetArticles virtual.

protected virtual void GetArticles()
{
}

Normal Class can not contain abstract method.Whereas abstract class can contain normal method. If a normal class inherit abstract class and hold any abstract method than must be override due to inheritance in derived class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM