Sealed Classes

Sealed class are classes that cannot be inherited by other class. Since sealed-classes cannot be inherited, they cannot be abstract. The following program shows an example of a sealed-class.

namespace SealedClassesDemo
{
    public sealed class Base
    {
        private int someField;
 
        public int SomeProperty
        {
            get { return someField; }
            set { field = value; }
        }
 
        public void SomeMethod
        {
            //Do something here
        }
 
        //Constructor
        public Base()
        {
            //Do something here
        }
    }
 
    public class Derived : Base // ERROR
    {
        //This class cannot inherit the Base class
    }
}

We use the sealed keyword to indicate that a class is a sealed-class. You can see that sealed-classes are just like normal classes so it can also have fields, properties and methods. Line 25 will produce an error because the Derive class is deriving from the sealed Base class. Sealed classes are useful if you are making a class that prohibits itself from being inherited by others.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *