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.
Let's start by defining a simple base class:
In this C# example, the Person
class includes:
Name
andAge
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.
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
andAge
properties and theDisplay
method from thePerson
class. - Adds a new property,
Major
. - Provides a new method,
DisplayStudent
, that calls the base classDisplay
method and prints the student's major. - Uses the
base
keyword to call the constructor and methods of thePerson
class.
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 theDisplayStudent
method, which internally calls theDisplay
method inherited from thePerson
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.
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!
