In the following code we tag the parent class (Vehicle) method with virtual and Child class (Bus) method with override.
using System; class Vehicle/* www.j a v a2s .c om*/ { public virtual void ShowMe() { Console.WriteLine("Inside Vehicle.ShowMe"); } } class Bus : Vehicle { public override void ShowMe() { Console.WriteLine("Inside Bus.ShowMe"); } public void BusSpecificMethod() { Console.WriteLine("Inside Bus.ShowMe"); } } class Program { static void Main(string[] args) { Vehicle obVehicle = new Bus(); obVehicle.ShowMe();//Inside Bus.ShowMe // obVehicle.BusSpecificMethod();//Error //Bus obBus = new Vehicle();//Error } }
The child class method is invoked, not the parent class method, since we tagged ShowMe() method in the Vehicle class as virtual.
When we call a child's method via a base class reference, the compiler uses the base type reference to invoke the child's method.
By marking a method in the base class as virtual, we intend to achieve polymorphism.
In this way we intentionally redefine/override the method in the child classes.
In the child class, by tagging a method with the keyword override, we tells the compiler that we will redefine the corresponding virtual method.
In C#, all methods are by default non-virtual.
But, in Java, they are virtual by default.
In C# we need to tag the keyword override to avoid any unconscious overriding.