Reinforcing Inheritance Concepts in C#
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:
NameandAgeproperties.- A constructor to initialize these properties.
- A
Displaymethod 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
NameandAgeproperties and theDisplaymethod from thePersonclass. - Adds a new property,
Major. - Provides a new method,
DisplayStudent, that calls the base classDisplaymethod and prints the student's major. - Uses the
basekeyword to call the constructor and methods of thePersonclass.
Testing Inheritance
