Cannot change access modifiers when overriding 'public' inherited member '

后端 未结 1 743
后悔当初
后悔当初 2020-12-07 04:29

I want to do adapter template.
There is error in AutoToTravelAdapterMove(); method How can I override and inherit Tra

相关标签:
1条回答
  • 2020-12-07 04:51

    The title is very clear - an override method must match the virtual method it overrides, not only by it's signature (name and parameters), but also by it's access modifiers and return type.
    Why? because of (at least) Polymorphism and method overloading rules.

    Polymorphism which is a base principle of object oriented programming is basically the ability to look at a derived class as if it was it's base class. This means that if the base class have a method like public void move(), the derived class also have this method - either inherited unchanged or overrided in the derived class.

    The rule for method overloading is very simple - you can have multiple methods with the same name but different signature. The signature of the method is the combination of it's name and it's arguments - so overloads that differs only by return type or access modifiers are not permitted.

    Imagine if the compiler would allow you to change the access modifier in inheritance - you would end up with a class like this:

    WARNING: Incorrect code ahead!

    public class Transport
    {
       public virtual void Move() { Console.WriteLine("trans Moves"); }
    }
    
    public class AutoToTravelAdapter : Transport
    {
        private Auto auto = new Auto();
        private override void  Move()
        {
            auto.Drive();
        }
    }
    

    So AutoToTravelAdapter would have, in fact, two Move methods with identical signature - one private that is declared in AutoToTravelAdapter class, and one public that is inherited from Transport.
    Obviously, this would make calling the Move() method from inside the AutoToTravelAdapter class impossible, since the compiler would have no way to distinguish between the two methods.

    0 讨论(0)
提交回复
热议问题