Welcome back! After learning to initialize objects with constructors, we’re ready to tackle another cornerstone of object-oriented programming: inheritance. This powerful feature allows us to create a new class based on an existing class, facilitating code reuse and organizing our programs more intuitively. Ready to explore how? Let’s dive in!
In this lesson, you will learn what inheritance is and how to use it in C#. Specifically, you will understand how to:
- Create a base class.
- Derive a new class from that base class.
- Use inherited attributes and methods in your derived class.
Consider the following example, where we have a CelestialBody class and a Planet class that inherits from it:
By the end of this lesson, you will be able to create hierarchical class structures, fostering better code organization and reuse.
When creating a derived class, you often need to initialize both the inherited attributes and any new attributes specific to the derived class. This is done through the derived class's constructor.
In the Planet class, we see an example of this:
Here's a breakdown of how this works:
public Planet(string name, string orbitingStar): This defines the constructor for thePlanetclass, accepting parameters for both the inherited and new attributes.: base(name): Thebasekeyword is used to call the constructor of the base class (CelestialBody). This initializes thenameattribute inherited fromCelestialBody.this.orbitingStar = orbitingStar;: We ensure that theorbitingStarattribute of the child class is correctly initialized.
By correctly using constructors, you ensure that all attributes, both inherited and new, are properly initialized when an object of the derived class is created.
