Understanding Sealed and Abstract classes using C#

Sealed and Abstract are keywords in C#. They have a special meaning and difference even though there is a wide similarity between these two terms.

When a base class is declared with sealed keyword, then that class cannot be extended. This is same as final keyword in Java.

Listing 1

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">public sealed class Computer 
{ 
//code goes here 
} 
class COMPAQ:COMPUTER 
{ 
//Not allowed as base class is sealed 
}


Abstract Classes

Abstract class is a special type of class, which should be declared with abstract keyword. Moreover, it should contain one or more abstract methods, which should contain only method definitions. It won’t be having any method body (in the form of curly braces) like Instance and Static methods.

Normally, a base class is declared with abstract keyword and the derived classes should extend the abstract class and implement relevant methods. Keep in mind that only one abstract class can be extended at a time since C# won’t supports multiple inheritance. Listing 2 illustrates this concept clearly:

Listing 2

<pre style="background-color: #ffffff; margin: 0em; width: 100%; font-family: consolas,&#39;Courier New&#39;,courier,monospace; font-size: 12px">using System; 
abstract public class Absdemo 
{ 
public abstract void Show(); 
} 
class Absimp:Absdemo 
{ 
public override void Show() 
{ 
Console.WriteLine(&quot;Abstract Method Implemented&quot;); 
} 
public static void Main(string[] args) 
{ 
Absimp ai = new Absimp(); 
ai.Show(); 
} 
} 



READ  Undertanding Arrays & Inheritance using Java

Leave a Reply

Your email address will not be published.