Reinforcing Inheritance Concepts in C#

Welcome back! Now that you have a solid understanding of classes and objects in C#, it's time to build on that knowledge by exploring inheritance. Consider it a natural progression in our journey into object-oriented programming (OOP).

Inheritance allows you to create a new class based on an existing class. By using inheritance, you can reuse code, add new features, and make your programs easier to manage and understand. Let's dive in and see what it's all about.

Base Class: Person

Let's start by defining a simple base class:

In this C# example, the Person class includes:

  • Name and Age properties.
  • A constructor to initialize these properties.
  • A Display method to print out the name and age.

This class serves as the base class from which other classes can inherit.

Derived Class: Student

Now, we define a derived class that inherits from the base class:

In this example, the Student class inherits from the Person class:

  • Reuses the Name and Age properties and the Display method from the Person class.
  • Adds a new property, Major.
  • Provides a new method, DisplayStudent, that calls the base class Display method and prints the student's major.
  • Uses the base keyword to call the constructor and methods of the Person class.
Testing Inheritance

Finally, let's test the inheritance by creating and using objects of the derived class:

In this code:

  • We create a Student object.
  • The student object calls the DisplayStudent method, which internally calls the Display method inherited from the Person class and then prints the major.

This demonstrates how inheritance allows for code reuse and maintains fundamental behavior while introducing new features in derived classes.

Conclusion

Inheritance in C# allows you to build on existing classes and reuse code efficiently. By using inheritance, you can create a class hierarchy that mirrors real-world relationships and provides a clear and maintainable structure for your applications.

Understanding and leveraging inheritance will enable you to design flexible, scalable, and organized object-oriented applications. With inheritance, you can extend existing functionalities, reduce code duplication, and develop more robust and readable programs.

Excited to start practicing? Let's move on and put this theory into action!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal