![]() |
VOOZH | about |
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed and therefore, cannot be extended. No class can be derived from a sealed class.
Syntax:
sealed class class_name
{
// data members
// methods
.
.
.
}
A method can also be sealed and in that case, the method cannot be overridden. However, a method can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be declared as virtual in its base class.
Example 1: Create a Sealed Class that can be used in Geeks Class
Total = 10
Example 2: When we try to inherit a class from a sealed class, an error will be produced stating that "It cannot be derived from a Sealed class"
Output:
./Solution.cs(13,7): error CS0509: `Example': cannot derive from sealed type `Test'
./Solution.cs(8,14): (Location of the symbol related to previous error)
Compilation failed: 1 error(s), 0 warnings
Example 3: Program to define Sealed Class Method
Display dimension : 6*6 Printer printing.... Display dimension : 12*12 Laserjet printer printing.... Display dimension : 12*12 Officejet printer printing....