What is Sealed Class:-
A sealed class can not be inherited. No class can be drived from sealed class.
Using Sealed keywords.
Note: we can create instance of sealed class.
Example:
sealed class A{
}
public classB:classA // we can not inherit the class b/c it is sealed. it gets compile error.
{
}
Sealed Method:-
Prevent overriding a method of a class.
A sealed class can not be inherited. No class can be drived from sealed class.
Using Sealed keywords.
Note: we can create instance of sealed class.
Example:
sealed class A{
}
public classB:classA // we can not inherit the class b/c it is sealed. it gets compile error.
{
}
Sealed Method:-
Prevent overriding a method of a class.
Why Sealed Classes?
We just saw how to create and use a sealed class in C#. The main purpose of a sealed class is to take away the inheritance feature from the class users so they cannot derive a class from it. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace.
The Pens class represents the pens with standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color.
So when you're designing a class library and want to restrict your classes not to be derived by developers, you may want to use sealed classes.
Example:
No comments:
Post a Comment