- Back to Home »
- C#.NET »
- C#.NET Sealed Class
Posted by :
Sudhir Chekuri
Tuesday, 5 January 2016
- A class which cannot be inherited by any other class is known as Sealed class.
- It should be declared using "sealed" keyword.
- Sealed classes are used to restrict the inheritance feature of object oriented programming.
- Once a base class is defined as Sealed class,this class cannot be inherited.
- If a class is derived from a Sealed class, compiler throws an error.
sealed class classname
{
//methods
}
class classname2:classname//Invalid because derived class will not inherit sealed class.
Example for sealed class
Program
using System;
namespace SealedClass
{
class Program
{
static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console.WriteLine("Total = " + total.ToString());
Console.ReadKey();
}
}
// Sealed class
sealed class SealedClass
{
public int Add(int x, int y)
{
return x + y;
}
}
}
Output
Total = 9