Why we use virtual and override keywords in c#

inheritance

Can anyone explain me what's the point of overriding base class implementations (if its not abstract), because it's not ethical move to modify features of the parent class according to the wishes of derived classes. The best way is to make the base classes abstract and carry on the inheritance chain. Whereas when designing a class hierarchy initially we gather or elicit all the essential requirements/features that should be belonged to a base class. Therefore, in a middle of a project we do not need to change base class implementations. According to my knowledge, base class implementation should be a constant. Thus, under this aspect, there's no real use of "override" keyword in c#. If it's not so please explain me with an example.

Best Answer

Many times you will have dependencies in sub-classes, or may have to implement things differently.

class BasicCarModel
{
    public virtual void Accelerate(double speed)
    {
         RotateFrontWheels(speed);
    }
}

class LuxuryCarModel : BasicCarModel
{
    public override void Accelerate(double speed)
    {
        RotateAllWheels(speed);
    }
}

There is nothing at all wrong with creating virtual methods in concrete classes and in some cases they are very useful. The difficulty is that many novice programmers violate the Liskov Substitution Principle when doing so. Remember that an overridden method should appear to do the same thing if used as a base method. It should not strengthen or weaken the preconditions of the base method.

In the example I gave, the difference between the base class and the derived class was in the mechanics of how the car accelerated, not in the values allowed for speed. It did not throw any exceptions that were not expected by a calling class.

This is a contrived example, but the principle is the same. Do use virtual and override when needed. Don't violate the LSP.

Related Topic