Understanding Method Overriding

Welcome! Building on our discussion of inheritance, we'll now explore method overriding. This allows a subclass to provide a specific implementation of a method that is already defined in its superclass, thus giving you more control over behavior in derived classes. Ready to enhance your skills further? Let’s jump in!

What You'll Learn

In this lesson, you will learn the essentials and intricacies of method overriding in C#. Specifically, you'll understand how to:

  • Define a virtual method in a base class.
  • Override that method in a derived class.
  • Use overridden methods to achieve polymorphism.

Consider the code from our example:

class CelestialBody 
{
    // Virtual method
    public virtual void MakeSound()
    {
        Console.WriteLine("The celestial body emits a sound");
    }
}

class Star : CelestialBody
{
    // Override the base class method
    public override void MakeSound()
    {
        Console.WriteLine("The star hums melodiously");
    }
}

class Program
{
    static void Main()
    {
        // Create an object of the Star class
        Star sun = new Star();
        // Call the overridden method
        sun.MakeSound();
    }
}

This example demonstrates how a Star class overrides the MakeSound method from the CelestialBody base class to provide a more specific implementation.

How Overriding Works in C#

In C#, the virtual keyword in a base class allows a method to be overridden in a derived class. The override keyword in the derived class provides the new implementation.

Without the virtual keyword, the method in the base class cannot be overridden. Instead, a method with the same name in the derived class will hide the base class method, but the base class method will still be called if the object is treated as an instance of the base class.

Overriding vs Hiding

Overriding uses the virtual keyword in the base class and the override keyword in the derived class. This ensures the derived class method replaces the base class method when called.

If you don’t use these keywords, the derived class method hides the base class method. This can cause confusion and errors because the base class method will still be called if the object is accessed as an instance of the base class. Therefore, using overriding is important for ensuring predictable and consistent behavior in your code.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal