Question

I'm trying to override an abstract method in an abstract class with a virtual method in a child class. I (assumed until now?) understand the difference between abstract and virtual methods.

Obviously I'm not able to do it but my question is... why? Based on the accepted answer here and the following scenario, I just don't see the problem:

    public abstract class TopLevelParent
    {
        protected abstract void TheAbstractMethod();
    }

    public class FirstLevelChild1 : TopLevelParent
    {
        protected override void TheAbstractMethod()
        {

        }
    }

    public class FirstLevelChild2 : TopLevelParent
    {
        protected virtual override void TheAbstractMethod()
        {
            //Do some stuff here
        }
    }

    public class SecondLevelChild : FirstLevelChild2
    {
        //Don't need to re-implement the method here... my parent does it the way I need.
    }

So obviosuly what I've done is have a top-level parent with two inheriting children and another class inheriting from one of those. Again, based on the accepted answer in the link I posted above:

"A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality."

and that the second level child will inherit the virtual method from its parent, thus satisfying the implementation requirement of the abstract method from its top-most parent... what's the problem?

I'm missing some detail somewhere that's hindering my understanding of this...

Was it helpful?

Solution

An override method is implicitly virtual (in the sense that it can be overridden in a subclass), unless marked as sealed.

Observe:

public class FirstLevelChild1 : TopLevelParent
{
    protected override void TheAbstractMethod() { }
}

public class SecondLevelChild1 : FirstLevelChild1
{
    protected override void TheAbstractMethod() { } // No problem
}

public class FirstLevelChild2 : TopLevelParent
{
    protected sealed override void TheAbstractMethod() { }
}

public class SecondLevelChild : FirstLevelChild2
{
    protected override void TheAbstractMethod() { } 
    // Error: cannot override inherited member 
    // 'FirstLevelChild2.TheAbstractMethod()' because it is sealed
}

OTHER TIPS

An abstract method is already virtual all the way down the inheritance chain - there's no need to declare it virtual in a subclass to allow the subclass to override it - the subclass can already override it.

If you don't provide an implementation, the closest implementation (looking down the inheritance list) will be used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top