Learning Management Platform for Written Tutorial Series.

C# Inheritance

C# Inheritance

Introduction

Inheritance is the ability of a child class to inherit properties and methods from a parent class. Let's say you want to create a program that records data about animals, you can create a class with common animal properties such as number of legs, sounds that the animal makes, food type etc.

All other animal classes i.e. hyena, lion, goat etc. can extend the parent class and inherit the properties and methods defined in the parent class.

Topics to be covered

  • Inheritance terminologies
  • Extending base classes
  • Calling the base class constructor
  • C# access modifiers inheritance
  • Virtual Methods
  • Overriding base methods

Inheritance terminologies

The following are some of the important terminologies that you will need to know about inheritance

  • base class: this is the parent class that child classes extend
  • derived class: this is a child class that extends a parent class
  • extend: inheriting properties and methods from the parent class.

Extending base classes

The syntax for extending base classes is as follows

class BaseClass{
    //define properties/methods
}

class DerivedClass : BaseClass{
    //do something
}

HERE,

  • class BaseClass{...} defines a parent class named BaseClass, and properties and methods.
  • class DerivedClass : BaseClass{...} defines a child class that inherits from BaseClass. Inheritance is specified using the full colon.

Rules of Inheritance

  1. A child class can only inherit from a parent class that was designed to allow inheritance. Private , sealed classes etc. do not allow inheritance
  2. A parent class that allows inheritance should be declared with as private, sealed, protected etc.

Practical Example

Animal base class

  1. Create a new console project in Visual Studio and name it CSharpInheritance
  2. Create a new class Animal.cs

Replace the code with the following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
class Animal
{
    protected string name;
    protected int legs;
    protected string food;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Legs {
        get { return legs ;}
        set { legs = value;} 
    }

    public string Food {
        get { return food; }
        set { food = value; } 
    }

    public void describeAnimal()
    {
        Console.WriteLine(name + " has " + legs + " legs and eats " + food);
    }
}
}

Hyena derived class

Add a new class Hyena.cs

Add the following code to Hyena.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
    class Hyena : Animal
    {

    }
}

Let's now test our project.

Add the following code to Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Hyena hyena = new Hyena();

            hyena.Name = "Hyena";
            hyena.Food = "Meat";
            hyena.Legs = 4;
            hyena.describeAnimal();

            Console.ReadLine();
        }
    }
}

Press F5 on the keyboard. You will get the following output in the console window.

Hyena has 4 legs and eats Meat

Calling the base class constructor

A constructor is the method that is executed when a class is initialized. Let's say we want to set the animal name, number of legs and the food type during class initializing.

Modify Animal.cs to the following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
    class Animal
    {
        protected string name;
        protected int legs;
        protected string food;

        public Animal(){}

        public Animal(string parName, int parLegs, string parFood)
        {
            this.name = parName;
            this.legs = parLegs;
            this.food = parFood;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public int Legs {
            get { return legs ;}
            set { legs = value;} 
        }

        public string Food {
            get { return food; }
            set { food = value; } 
        }

        public void describeAnimal()
        {
            Console.WriteLine(name + " has " + legs + " legs and eats " + food);
        }
    }
}

HERE,

  • public Animal(){} defines a constructor that doesn't do much
  • public Animal(string parName, int parLegs, string parFood){...} defines a constructor that accepts three parameters and assigns them to the member variables name,legs,food

Derived class that calls parent constructor

Add a new class Dog.cs

Add the following code to Dog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
    class Dog : Animal
    {
        public Dog(string parName, int parLegs, string parFood) : base(parName, parLegs, parFood)          
        {

        }
    }
}

HERE,

  • class Dog : Animal defines the class Dog and extends the base class Animal
  • public Dog(string parName, int parLegs, string parFood) : base(parName, parLegs, parFood) defines a constructor method that extends the base constructor with the same signature. The full colon is used to extend the base constructor. The value of parName, parLegs, parFood are passed to the base constructor.

Open Program.cs

Modify it to the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Hyena hyena = new Hyena();

            hyena.Name = "Hyena";
            hyena.Food = "Meat";
            hyena.Legs = 4;
            hyena.describeAnimal();

            Dog dog = new Dog("German Shepherd", 4, "Meat");
            dog.describeAnimal();

            Console.ReadLine();
        }
    }
}

Let's now run our project and see the results.

Press F5 on the keyboard, you will get the following results.

Hyena has 4 legs and eats Meat
German Shepherd has 4 legs and eats Meat

C# access modifiers inheritance

Controlling the visibility of properties and methods is very important for control purposes. In this section, we will look at three access modifiers;

  • private - all properties and methods defined as private can only be accessed within the class itself. If you have a private class property or method in a base class, then the derived class will not be able to access the property or method.
  • protected - all properties and methods defined as protected can be accessed both within the base and the derived class.
  • public - all properties and methods defined as public can be accessed within the base, derived and outside class.

Virtual Methods

Our Animal class defined a method describeAnimal and provided the implementation. What if you would like to modify the implementation of describeAnimal in the derived class? How would you accomplish that?

This is what virtual methods are for. The virtual keyword is used to define methods whose implementation can be overridden in the specialized class.

Syntax for virtual methods

public virtual void methodName()
{
    //provide initial implementation
}

HERE,

  • The virtual keyword is used to define a method as virtual.

Rules for defining virtual methods

  • A virtual method cannot be declared as private. This is because the derived class will not be able to access and override it.
  • A virtual method cannot be declared as static. This is because polymorphism operates on instances of classes and not the classes themselves.

Practical Example virtual methods

Add the following virtual method to Animal class

public virtual void behaviour()
{
    Console.WriteLine(name + " has animal behaviour");
}

Overriding base methods

Overriding is what allows us to change the implementation of a virtual method that is defined in a base class. The following syntax is used to override virtual methods.

Syntax for overriding methods

public override void methodName()
{
    //provide specialized implementation
}

HERE,

  • The override keyword is used to alter the default implementation of the method.

Rules for defining virtual methods - You can only override identical methods - An override method cannot be private - An override method cannot be static - An override method must match the virtual method

Practical Example virtual methods

Add the following override method to Dog class

public override void behaviour()
{
    Console.WriteLine("This behaviour has been overriden");
}

Modify Program.cs to the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpInheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Hyena hyena = new Hyena();

            hyena.Name = "Hyena";
            hyena.Food = "Meat";
            hyena.Legs = 4;
            hyena.describeAnimal();
            hyena.behaviour();

            Dog dog = new Dog("German Shepherd", 4, "Meat");
            dog.describeAnimal();
            dog.behaviour();

            Console.ReadLine();
        }
    }
}

Press F5 on the keyboard to run the program.

You will get the following results.

Hyena has 4 legs and eats Meat
Hyena has animal behaviour
German Shepherd has 4 legs and eats Meat
This behaviour has been overridden

Summary

  • Inheritance is the ability of a derived class to inherit properties and methods from a parent class
  • Sealed classes cannot be inherited
  • Private properties/methods can only be seeing within the class itself. Protected properties/methods can be accessed both within the base and derived classes. public properties/methods can be accessed both within and outside a class
  • Derived classes can override virtual methods.

Tutorial History

Tutorial version 1: Date Published 2015-08-21


...