C# Method Overriding

Method Overriding

Method overriding in C# is a feature of object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This means that the subclass method replaces the implementation of the same method in the superclass.

To perform method overriding in C#, you need to use the virtual keyword with a base class method and override the keyword with a derived class method.

Why Use Method Overriding?

Flexibility and Specialization: Derived classes can adapt inherited methods to their specific needs, promoting code reusability and polymorphism (the ability of objects to respond differently to the same message).

Extending Functionality: You can add new behavior to inherited methods while preserving the core functionality from the base class.

Elegant Design: Method overriding fosters well-structured and maintainable code by promoting code reuse and clear inheritance hierarchies

Scenario: Imagine you are creating a virtual animal simulation. In this simulation, different animals can make sounds. There is a general sound that any animal might make, but specific animals like dogs have their unique sounds. You will create a program to represent this using inheritance and method overriding.

Write a program where an Animal class has a method Bark that describes a generic animal sound. Then, create a Dog class that inherits from Animal and overrides the Bark method to provide a specific sound for dogs.

Example :

using System;
class Animal
{
    public virtual void Sound()
    {
        Console.WriteLine(“The animal makes a generic sound.”);
    }
}
class Dog : Animal
{
    public override void Sound()
    {
        Console.WriteLine(“The dog barks: Woof! Woof!”);
    }
}
class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog();
        myDog.Sound(); 
    }
}

Output: The dog barks: Woof! Woof!

Example :

using System;
class Animal

Defines a new class named Animal.

public virtual void Sound()

Declares a virtual method Sound in the Animal class. Virtual methods can be overridden in derived classes.

Console.WriteLine(“The animal makes a generic sound.”);

print the message in console.

class Dog : Animal

Defines a new class named Dog that inherits from the Animal class by using colon sign – “:”.

public override void Sound()

Overrides the Sound method in the Animal class. The override keyword indicates this method replaces the base class method.

Console.WriteLine(“The dog barks: Woof! Woof!”);

print message in console.

class Program

Defines a new class named Program.

static void Main(string[] args)
    {
        Dog myDog = new Dog();

Creates a new instance of the Dog class.

myDog.Sound();

Calls the Sound method on the Dog instance. This will output the dog-specific barking sound.

Course Video :
Course Video English :
Task:

1. Basic Overriding:
Write a base class Shape with a virtual method Draw(). Create a derived class Circle that overrides the Draw() method to print “Drawing Circle”.

2. Polymorphism with Overriding:
Define a base class Animal with a virtual method MakeSound(). Create derived classes Dog and Cat that override MakeSound() to print “Bark” and “Meow” respectively. Demonstrate polymorphism by calling MakeSound() on a list of Animal objects.

3. Calling Base Class Method:
Create a base class Vehicle with a virtual method Describe(). In a derived class Car, override Describe() but also call the base class Describe() method within the overridden method.

4. Abstract Methods:
Write an abstract class Employee with an abstract method CalculateSalary(). Create derived classes FullTimeEmployee and PartTimeEmployee that implement the CalculateSalary() method.

5. Overriding Properties:
Define a base class Person with a virtual property Name. Create a derived class Student that overrides the Name property to add custom behavior when setting the property value.

6. Overriding ToString() Method:
Write a class Book that overrides the ToString() method to return a string representation of the book’s title and author.

7. Sealed Method:
Create a base class BaseLogger with a virtual method Log(). In a derived class FileLogger, override the Log() method and mark it as sealed. Then create another derived class DetailedFileLogger and demonstrate that Log() cannot be overridden further.

8. Overriding Equals() Method:
Write a class Point that overrides the Equals() method to compare two points based on their x and y coordinates.

9. Virtual Method with Parameters:
Define a base class Printer with a virtual method Print(string message). Create a derived class ColorPrinter that overrides the Print(string message) method to print the message in color.

10. Overriding with Different Access Modifiers:
Write a base class BankAccount with a protected virtual method CalculateInterest(). Create a derived class SavingsAccount that overrides CalculateInterest() with a public modifier, and demonstrate how this change affects method visibility.

Frequently Asked Questions

Still have a question?

Let's talk

Method overriding in C# allows a derived class to provide a specific implementation for a method already defined in its base class.

Method overriding is achieved by using the virtual keyword in the base class method and the override keyword in the derived class method.

Method overriding provides polymorphic behavior, enabling different implementations of a method depending on the object type.

No, static methods cannot be overridden because they belong to the class, not the instance.

  • Overloading: Same method name but different signatures in the same class.
  • Overriding: Redefines a method’s behavior in the derived class.

Only virtual, abstract, or already overridden methods can be overridden in a derived class.

The base keyword is used to call the overridden method of the base class within the derived class.

  • The base method must be marked as virtual, abstract, or override.
  • The overriding method must have the same signature as the base method.

Yes, by using the sealed keyword with the method in a derived class.

If override is not used, the method in the derived class will hide the base class method instead of overriding it.

 

Iqra Technology Academy offers free video tutorials in Hindi that explain method overriding in C#. These tutorials include practical examples, explanations, and use cases to help you grasp the concept of method overriding in C# with ease.

Iqra Technology Academy provides a free online course in Hindi on method overriding in C#. The course includes detailed explanations, examples, and hands-on exercises to help you understand and implement method overriding effectively.

Method overriding is used in C# to provide specific functionality in the derived class while retaining the same method signature as the base class. This allows derived classes to alter the behavior of methods inherited from the base class, providing flexibility and code reuse.

Iqra Technology Academy provides comprehensive tutorials and a free online course in Hindi on method overriding in C#. Our resources will guide you through the concept step by step, helping you understand and apply method overriding in your C# projects.