What is Sealed Class?

Forums C#What is Sealed Class?
Staff asked 2 years ago

Answers (2)

Add Answer
monika gabani Marked As Accepted
Staff answered 2 years ago

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword.

Once a class is defined as a sealed class, this class cannot be inherited.

A method can also declared as sealed in that case it can not be override.

Example:

using System;
 
sealed class SealedClass {
 
    public int Multiply(int a, int b)
    {
        return a * b;
    }
}
 
class Program {

    static void Main(string[] args)
    {
        SealedClass slc = new SealedClass();
        int total = slc.Multiply(10, 15);
        Console.WriteLine("Total = " + total.ToString());
    }
}

Output: Total = 150

Staff answered 2 years ago

A Sealed class is a class that cannot be inherited and used to restrict the properties.

The following are some key points:

  • A Sealed class is created using the sealed keyword.
  • Access modifiers are not applied to a sealed class.
  • To access the sealed members, we must create an object of the class.

Example

using System;
sealed class SealedClass {
 
    // Calling Function
    public int Addition(int a, int b)
    {
        return a + b;
    }
}
class Program {
     static void Main(string[] args)
    {
         // Creating an object of Sealed Class
        SealedClass slc = new SealedClass();
 
        // Performing Addition operation
        int total = slc.Addition(5, 5);
        Console.WriteLine("Total = " + total.ToString());
    }
}
  • You can inherit the sealed class it gives an error.
using System;
 
// Creating a sealed class
sealed class SealedClass {
}
 
// Inheriting the Sealed Class
class Example : SealedClass {
}
 
// Driver Class
class Program {
     // Main Method
    static void Main()
    {
    }
}

It gives an error

Subscribe

Select Categories