Home > other >  Why must an abstract method be protected in a derived class?
Why must an abstract method be protected in a derived class?

Time:03-16

When inheriting from an abstract class, why can't the protected abstract methods in an abstract base class be private when they are overridden in an abstract derived class?

Rephrasing, is it possible for an abstract method to be defined by a child abstract class, but then not accessible by a grandchild class?

Consider the simplified example:

public abstract class A
{
    // This method is protected - makes sense
    protected abstract void M();
}

public abstract class B : A
{
    // Why can't this be private?
    // Compiler forces it to be protected
    // but this means grandchildren classes always have access to this method
    protected override void M()
    {
        // Do something
    }
}

public class C : B
{
    // Is it possible for M() to be inaccessible here?
}

CodePudding user response:

The grandchild class C also implements the parent class A, so it's not possible. After all, in a program, you could cast any C object to a variable of type A, and you would expect to be able to call the M() method on it. It would not make sense for a child class not to implement all the members of its parents, regardless of the inheritance hierarchy level.

CodePudding user response:

I don't believe this is possible due to how inheritance works. All children (derived classes) have everything a parent has, plus whatever extra stuff you need.

That said - if you want a child class to NOT have one of the methods its parent has, you can do it with interfaces. Simply define an interface which lacks the one method you want to restrict, and have both parent and child implement it.

But back to what @Jon Skeet said above. Why?

  • Related