Chapter 6. Inheritance
Inheritance is one of the fundamental concepts in object-oriented programming. Inheritance facilitates code reuse and allows you to extend the functionality of code that you have already written. This chapter looks at:
How inheritance works
Implementing inheritance in C#
Defining abstract methods and classes
Sealing classes and methods
Defining overloaded methods
The different types of access modifiers you can use in inheritance
Using inheritance in interfaces
Understanding Inheritance in C#
The following Employee
class contains information about employees in a company:
public class Employee { public string Name { get; set; } public DateTime DateofBirth { get; set; } public ushort Age() { return (ushort)(DateTime.Now.Year - this.DateofBirth.Year); } }
Manager
is a class containing information about managers:
public class Manager { public string Name { get; set; } public DateTime DateofBirth { get; set; } public ushort Age() { return (ushort)(DateTime.Now.Year - this.DateofBirth.Year); } public Employee[] subordinates { get; set; } }
The key difference between the Manager
class and the Employee
class is that Manager
has an additional property, subordinates
, that contains an array of employees under the supervision of a manager. In fact, a manager is actually an employee, except that he has some additional roles. In this example, the Manager
class could inherit from the Employee
class and then add the additional subordinates
property that it requires, like this:
public class ...
Get C# 2008 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.