Understanding Sealed and Abstract classes using C#


0

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

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

using System; 
abstract public class Absdemo 
{ 
public abstract void Show(); 
} 
class Absimp:Absdemo 
{ 
public override void Show() 
{ 
Console.WriteLine("Abstract Method Implemented"); 
} 
public static void Main(string[] args) 
{ 
Absimp ai = new Absimp(); 
ai.Show(); 
} 
} 



Like it? Share with your friends!

0

What's Your Reaction?

hate hate
0
hate
confused confused
0
confused
fail fail
0
fail
fun fun
0
fun
geeky geeky
0
geeky
love love
0
love
lol lol
0
lol
omg omg
0
omg
win win
0
win
Anand Narayanaswamy
Anand Narayanaswamy is the editor-in-chief of Learnxpress. He was a Microsoft Most Valuable Professional (MVP) for a period of 9 years. He is a ASPInsider based in Trivandrum, Kerala State, India. Anand is the author of Community Server Quickly published by Packt Publishing.

0 Comments

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