Diving into Inheritance

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!

What You'll Learn

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:

class CelestialBody 
{
    // Attribute
    public string name;

    // Constructor
    public CelestialBody(string name)
    {
        this.name = name;
    }
}

class Planet : CelestialBody
{
    // Additional attribute specific to Planet class
    public string orbitingStar;

    // Constructor for both inherited and new attributes
    public Planet(string name, string orbitingStar) : base(name)
    {
        this.orbitingStar = orbitingStar;
    }

    // Method specific to Planet class
    public void Orbit()
    {
        Console.WriteLine(name + " is orbiting the star " + orbitingStar);
    }
}

By the end of this lesson, you will be able to create hierarchical class structures, fostering better code organization and reuse.

Understanding Constructors in Inheritance

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:

public Planet(string name, string orbitingStar) : base(name)
{
    this.orbitingStar = orbitingStar;
}

Here's a breakdown of how this works:

  • public Planet(string name, string orbitingStar): This defines the constructor for the Planet class, accepting parameters for both the inherited and new attributes.
  • : base(name): The base keyword is used to call the constructor of the base class (CelestialBody). This initializes the name attribute inherited from CelestialBody.
  • this.orbitingStar = orbitingStar;: We ensure that the orbitingStar attribute 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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal