Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide inherited protected method

Is it possible to hide or block a inherited protected virtual or protected abstract method so that further inheriting classes cannot access them?

For example:

class Base<T>
{
    protected abstract T CreateInstance();
}

class Derivative : Base<Derivative>
{
    protected sealed override Derivative CreateInstance()
    {
        return new Derivative();
    }
}

class MoreDerivative : Derivative
{
    public MoreDerivative()
    {
        // cannot access CreateInstance here
    }
}

I don’t think it is implemented in the language, but maybe there is an annotation or something like that.

like image 689
ominug Avatar asked Oct 19 '25 18:10

ominug


1 Answers

No. When you define a member for a type, you're saying that that type and all of it's sub-types will have that member. There is no way to "revoke" that. This assumption is an integral part of the type system.

You probably want to consider using composition here, rather than inheritance. Create a type that has a field of type Derivative, rather than inheriting from it.

like image 54
Servy Avatar answered Oct 22 '25 08:10

Servy