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 Bark()
    {
        Console.WriteLine(“The animal makes a generic sound.”);
    }
}
class Dog : Animal
{
    public override void Bark()
    {
        Console.WriteLine(“The dog barks: Woof! Woof!”);
    }
}
class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog();
        myDog.Bark(); 
    }
}

Output: The dog barks: Woof! Woof!

Example :

using System;
class Animal

Defines a new class named Animal.

public virtual void Bark()

Declares a virtual method Bark 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 Bark()

Overrides the Bark 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.Bark();

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

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.