(C# Language) Inheritance and protected and sealed keywords

Inheritance in C# is similar to what we have in other object oriented languages. In this tutorial we take a short example to get introduced to the syntax. We also learn about the protected and sealed keywords.
(Rev. 30-Sep-2022)

Categories | About |     |  

Parveen,

Area class

Consider a class called Area with two protected members for length and breadth. These members are accessible to the derived classes but not the external world.

The constructor accepts two arguments and saves the length and breadth.

  
class Area
{
  protected int length;
  protected int breadth;

  public Area(int l, int b)
  {
    length = l;
    breadth = b;
  }

  public virtual void Print()
  {
    int area = length * breadth;

    Console.WriteLine($"Area = {area}");
  }
}
  
  

Then we have a method called Print that prints the area of the figure. This has been marked virtual so that derived classes can over-ride and define their own Print method.

Video Explanation (see it happen!)

Please watch the following youtube video:

Volume class

Immediately next we have a class called Volume that inherits from Area. This class adds a member called height. This class has been marked as sealed so that it cannot be derived any further. We have used the keyword only for tutorial purposes, otherwise its usage depends on your specific code.

  
sealed class Volume : Area
{
  private int height;

  public Volume(int l, int b, int h) : base(l, b)
  {
    height = h;
  }

  public override void Print()
  {
    int vol = length * breadth * height;

    Console.WriteLine($"Volume = {vol}");
  }

}
  
  

The constructor takes three arguments and passes two of them to the Area class. The use of base keyword has been made for this purpose.

Finally, the print method has been over-ridden for displaying the volume. Notice that it was possible to access length and breadth because they are protected members of the Area class, and they are available to the derived class.

Main function

We can test the class by creating an object of the Volume class and printing it out.

Run the program to verify that the program compiles and prints the volume as expected.


class Program
{
  static void Main()
  {
    Volume v = new Volume(2, 3, 4);

    v.Print();
  }
}

  

This should get you started about the syntax of deriving a class in C#. Thanks!


This Blog Post/Article "(C# Language) Inheritance and protected and sealed keywords" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.