ian.blair@softstuff

My technical musings

Abstract vs Sealed classes in C#

One of the confusing things for a lot of newbie C# programmers writing Object Oriented code for the first time are the keywords Abstract and Sealed. Probably one of the easiest ways to remember when to use them is if you decide to inherit classes that abstract is used at the bottom of the pile, the base class, and sealed can be used at the top to stop any further inheritance.

public abstract class AbstractClass
{
	public AbstractClass() { }
	private void privatefunction() { }
	public void testfunction() { privatefunction(); }
}
 
public class InheritedClass : AbstractClass
{
	public InheritedClass() { }
	public void inheritedfunction() { }
}


public sealed class TopClass : InheritedClass
{
	public TopClass() { }
	public void topclassfunction() { }
}

 

Using the example classes above we can examine how the keywords work.

The base class AbstractClass is marked as abstract so this wont work. 

AbstractClass a = new AbstractClass(); // wont work

The abstract keyword stops an instance of this class being created with the new keyword, it just means that we can use this as a base class for further inheritance but we cant use it as a class in its own right.

To use the AbstractClass we have to inherit from it in a new class so the following works.

InheritedClass a = new InheritedClass();

Also we can now access the function in the AbstractClass called testfunction() so this will work.

a.testfunction();

But we cant access the private class that has been defined so this wont work.

a.privatefunction(); // wont work 

Or we can call the function that has been created in InheritedClass.

a.inheritedfunction();

But we can inherit further from InheritedClass to create the TopClass. So the following works. 

TopClass top=new TopClass();

top.testfunction(); 

However this time the definition of TopClass includes the sealed class so we can no longer use that as a base for further inheritance.

public class NewClass : TopClass // wont compile
{
 public NewClass() { }
}

This wont work and wont even compile as TopClass has been sealed.

Hopefully this gives a brief explanation of when to use abstract or sealed. In short abstract is used for a base class that shouldn't be used by itself, and sealed is used for classes that you don't want to be extended through further inheritance.