Sealed Class In C#

A sealed class is like a normal class but we cannot inherit it.

The Main use of the sealed class is to take the inheritance component from the class users so they cannot derive a class from it.

A sealed class is used to stop a class to be inherited.

A sealed class can restrict access to the classes and their members with the help of a sealed keyword and we can also avoid inheriting the defined classes from other classes.

Similarly if a method is declared using sealed keyword, we cannot override it.

A sealed class can define constructors in C#.

Let’s get started.

Step-1: create a new project and select a console application and click on the Next button

 

Step-2: give the project name and set it to the location and click on the Next button

 

Step-3: choose the target framework click on the Next button

Step-4:In the following code, I create a sealed class SealedClass and use it from Program class.

using System; 
// Sealed class  
public sealed class SealedClass  
{  
    public int Add(int x, int y)  
    {  
        return x + y;  
    }  
}  
class program
{  
    static void Main(string[] args)  
    {  
        SealedClass sealedCls = new SealedClass();  
        int total = sealedCls.Add(4, 5);  
        Console.WriteLine("Total = " + total.ToString());  
    }  
}  

 

Step-5:  Here is the output of the sealed class we created.

Step-6: if you try to derive a class from the SealedClass, you will get an error.

public class Animal
  {
      public virtual void eat() { Console.WriteLine("eating..."); }
      public virtual void run() { Console.WriteLine("running..."); }

  }
  public class Dog: Animal
  {
      public override void eat() { Console.WriteLine("eating bread..."); }
      public sealed override void run()
      {
          Console.WriteLine("running very fast...");
      }
  }
  public class BabyDog: Dog
  {
      public override void eat() { Console.WriteLine("eating biscuits..."); }
      //when we try to override sealed method error is generated
      //public override void run() { Console.WriteLine("running slowly..."); }
  }
  class Program
  {
      static void Main(string[] args)
      {
          BabyDog d = new BabyDog();
          d.eat();
          d.run();
      }
  }

 

when we  try to inherit a sealed class this is the compile-time error

Hope the concept of sealed class is clear.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories