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!
In this lesson, you will learn the essentials and intricacies of method overriding in C#
. Specifically, you'll understand how to:
virtual method
in a base class.Consider the code from our example:
C#1class CelestialBody 2{ 3 // Virtual method 4 public virtual void MakeSound() 5 { 6 Console.WriteLine("The celestial body emits a sound"); 7 } 8} 9 10class Star : CelestialBody 11{ 12 // Override the base class method 13 public override void MakeSound() 14 { 15 Console.WriteLine("The star hums melodiously"); 16 } 17} 18 19class Program 20{ 21 static void Main() 22 { 23 // Create an object of the Star class 24 Star sun = new Star(); 25 // Call the overridden method 26 sun.MakeSound(); 27 } 28}
This example demonstrates how a Star
class overrides the MakeSound
method from the CelestialBody
base class to provide a more specific implementation.
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 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.
Method overriding is a cornerstone of object-oriented programming as it enables polymorphism, allowing objects to interact seamlessly:
Imagine needing different types of celestial bodies, each with its unique MakeSound
method. Using overriding, you can manage these differences efficiently, keeping your code clean and easy to follow.
Are you excited to put this into practice? Let's move to the practice section and start coding!