Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. This promotes code reusability and establishes a natural hierarchy between classes.

Key Concepts

  1. Base Class (Parent Class): The class whose properties and methods are inherited.
  2. Derived Class (Child Class): The class that inherits from the base class.
  3. protected Access Modifier: Allows a member to be accessible within its class and by derived class instances.
  4. base Keyword: Used to access members of the base class from within a derived class.

Example

Let's start with a simple example to illustrate inheritance in C#.

Base Class

public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void Eat()
    {
        Console.WriteLine($"{Name} is eating.");
    }

    public void Sleep()
    {
        Console.WriteLine($"{Name} is sleeping.");
    }
}

Derived Class

public class Dog : Animal
{
    public string Breed { get; set; }

    public void Bark()
    {
        Console.WriteLine($"{Name} is barking.");
    }
}

Using the Derived Class

class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog
        {
            Name = "Buddy",
            Age = 3,
            Breed = "Golden Retriever"
        };

        myDog.Eat();  // Inherited method
        myDog.Sleep();  // Inherited method
        myDog.Bark();  // Method from Dog class

        Console.WriteLine($"My dog's name is {myDog.Name}, age is {myDog.Age}, and breed is {myDog.Breed}.");
    }
}

Explanation

  • Base Class (Animal): Contains properties Name and Age, and methods Eat and Sleep.
  • Derived Class (Dog): Inherits properties and methods from Animal and adds a new property Breed and a new method Bark.
  • Usage: An instance of Dog can access both its own members and the inherited members from Animal.

Practical Exercise

Task

Create a base class Vehicle with properties Make, Model, and Year, and methods Start and Stop. Then, create a derived class Car that adds a property NumberOfDoors and a method Honk.

Solution

Base Class

public class Vehicle
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }

    public void Start()
    {
        Console.WriteLine($"{Make} {Model} is starting.");
    }

    public void Stop()
    {
        Console.WriteLine($"{Make} {Model} is stopping.");
    }
}

Derived Class

public class Car : Vehicle
{
    public int NumberOfDoors { get; set; }

    public void Honk()
    {
        Console.WriteLine($"{Make} {Model} is honking.");
    }
}

Using the Derived Class

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car
        {
            Make = "Toyota",
            Model = "Camry",
            Year = 2020,
            NumberOfDoors = 4
        };

        myCar.Start();  // Inherited method
        myCar.Honk();  // Method from Car class
        myCar.Stop();  // Inherited method

        Console.WriteLine($"My car is a {myCar.Year} {myCar.Make} {myCar.Model} with {myCar.NumberOfDoors} doors.");
    }
}

Common Mistakes

  1. Forgetting to use the base keyword: When you need to call a base class constructor or method from the derived class.
  2. Incorrect access modifiers: Using private instead of protected for members that need to be accessible in derived classes.
  3. Not initializing base class properties: Ensure that base class properties are properly initialized in the derived class.

Additional Tips

  • Use inheritance to promote code reuse and establish a clear hierarchy.
  • Avoid deep inheritance hierarchies as they can become difficult to manage and understand.
  • Consider using interfaces or composition if inheritance does not fit well with your design.

Conclusion

Inheritance is a powerful feature in C# that allows you to create a new class based on an existing class. This promotes code reuse and helps in creating a clear and maintainable class hierarchy. In the next topic, we will explore polymorphism, which builds on the concept of inheritance to allow for more flexible and dynamic code.

© Copyright 2024. All rights reserved