Additional Topics on Inheritance
Explore how inheritance works in C#, focusing on member accessibility, including private, protected, and public modifiers. Understand how constructors in base and derived classes interact, and learn techniques for calling base class constructors explicitly or implicitly to manage object initialization.
We'll cover the following...
Inheritance is a powerful feature, but it comes with specific rules regarding member visibility and object initialization. This lesson explores which members are accessible to derived classes and how constructors are executed in an inheritance hierarchy.
Access the base class members
Inheritance facilitates code reuse, but we must determine exactly which members are inherited. We can answer this by trying to access base class members. Let’s consider an example:
public class EducationalOrganization{private string _name;public string Name{get { return _name; }}}public class School : EducationalOrganization{}
Lines 1–8: We define a base class
EducationalOrganizationwith a private field and a public property.Lines 10–12: We define a derived class
Schoolthat inherits fromEducationalOrganization.
The School class inherits from EducationalOrganization. We might assume that School inherits all members of EducationalOrganization, including the _name field.
First, let’s define the base class with a private field.
Line 3: We define the
EducationalOrganizationclass.Line 6: We declare a private field
_name.Lines 8–11: We provide a public property
Nameto expose the value of the private field.
Next, we define the derived class that inherits from this organization.