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
- Base Class (Parent Class): The class whose properties and methods are inherited.
- Derived Class (Child Class): The class that inherits from the base class.
protected
Access Modifier: Allows a member to be accessible within its class and by derived class instances.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 propertiesName
andAge
, and methodsEat
andSleep
. - Derived Class (
Dog
): Inherits properties and methods fromAnimal
and adds a new propertyBreed
and a new methodBark
. - Usage: An instance of
Dog
can access both its own members and the inherited members fromAnimal
.
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
- Forgetting to use the
base
keyword: When you need to call a base class constructor or method from the derived class. - Incorrect access modifiers: Using
private
instead ofprotected
for members that need to be accessible in derived classes. - 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.
C# Programming Course
Module 1: Introduction to C#
- Introduction to C#
- Setting Up the Development Environment
- Hello World Program
- Basic Syntax and Structure
- Variables and Data Types
Module 2: Control Structures
Module 3: Object-Oriented Programming
- Classes and Objects
- Methods
- Constructors and Destructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced C# Concepts
- Interfaces
- Delegates and Events
- Generics
- Collections
- LINQ (Language Integrated Query)
- Asynchronous Programming
Module 5: Working with Data
Module 6: Advanced Topics
- Reflection
- Attributes
- Dynamic Programming
- Memory Management and Garbage Collection
- Multithreading and Parallel Programming