Inheritance
Inheritance
Introduction to C# Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to define a
new class based on an existing class. In C#, inheritance enables you to create classes that share common
properties and behaviors, allowing for code reuse, logical hierarchy, and easier maintenance.
• The existing class is called the "base class" (or "parent" class), containing shared attributes and
methods.
• The new class is called the "derived class" (or "child" class), which inherits the base class's
properties and methods but can also introduce additional features that are specific to it.
Inheritance is useful when different types of objects share similar properties but also need to add unique
features. This setup allows us to write code in a structured, modular way.
In C#, inheritance is achieved by using a colon (:) followed by the name of the base class. For example, if
a Student class inherits from a Person class, it would be written as class Student : Person.
Let’s explore how inheritance works through a real-world example: building a simple school
management system. In this example:
• We start with a Person base class, which holds common attributes and behaviors for any person
in the school.
• From Person, we will create two specialized classes: Student and Teacher.
o Each derived class inherits the properties of Person but also includes unique attributes
and behaviors relevant to students and teachers.
Task: Create instances of Student and Teacher to test their properties and methods.
Expected Output
Extend the School Management System with New Roles and Properties:
• Add a Principal class that represents the school head. The Principal class should:
o Include a property YearsInService (an integer representing how long the principal has been in the
role).
o Add a method Announce() that prints an announcement like "Welcome! Let's have a great day at
school!".
o Add Principal Object and call the Introduce() and Annouce() methods.