Sunday, 6 May 2012

Can you prevent a class from being inherited?

Yes. How?

It seems that one can prevent a class from being inherited by using a certain keyword with that class. That keyword is 'sealed'. If you want to prevent 
a class in C# from being inherited, 'sealed' is used. So, this makes it clear that a sealed class may not serve as a base class of any other class. It is also clear that a sealed class cannot be an abstract class because an abstract class must be inherited. Here's a C# example,

sealed class XYZ
{
public int x;
public int y;
}

No class can inherit from XYZ defined above. Instances of XYZ may be created and its members may then be accessed, but nothing like the code below is possible.

class SomeClass : XYZ { } ... This cannot be done.

No comments:

Post a Comment