Ever heard of a class that is abstract
as well as sealed
? Sounds impossible, right? abstract
means some functions must be defined in the derived class and sealed
means class cannot be derived. Conflicting statements!!? Well, actually the catch is in the meaning of abstract
class. Creating abstract
class means that instance of a class cannot be created. That is why you can have the following class in C#:
public abstract class MyFundooClass
{
}
So now, you are clear that abstract
means class cannot be instantiated. But what if someone decided to derive your class and create an instance of it? For example:
public class MyFundooClassImpl : MyFundooClass
{
}
void SomeFunc()
{
MyFundooClass obj= new MyFundooClassImpl();
}
Here, the sealed
keyword comes to the rescue. Sealed
means class cannot be derived. So now, you can write your class as:
public abstract sealed class MyAbstractClass
{
}
Now, no one can derive your class, and no one can create any instance of it. Happy!! But, the question is why would anyone want to create a class that is abstract sealed
? And the answer is, ever heard of static
class?
public static class MyFundooClass
{
}
The static
class in C# are equivalent to abstract sealed
class. In fact, C# compiler won't let you write:
public abstract sealed class MyAbstractClass
{
}
But if you compile a static
class, and investigate the IL, you would be surprised to see that IL is:
.class public abstract auto ansi sealed beforefieldinit C_Sharp_ConsoleApp.MyFundooClass
extends [mscorlib]System.Object
{
}
So, a static
class in C# actually gets compiled into an abstract sealed
class!. And just because you cannot create any instance of such class, the compiler won't let you define any instance member, so you must have only static
members in such class.
Happy coding!!
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.