#621 – Sealing a Class to Prevent Inheritance

By default, a public class may be inherited from–by a class within the same assembly or even by a class in a different assembly.

To prevent your class from being used as a parent class, you can declare the class with the sealed keyword.  This “seals” the class, so that no one else can inherit from it.

    public sealed class Dog
    {
        public void Bark()
        {
            Console.WriteLine("Dog barking: Woof");
        }
    }

    // Compile-time error: Cannot derive from sealed type DogLibrary.Dog
    public class Terrier : Dog
    {
    }

A sealed class can’t be abstract–since the whole idea of an abstract class is that it is meant to serve as a base class for other classes.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: