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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…