Sealed class
A class which cannot inherits is called as sealed class
Sealed class classname
{
}
Note: all static classes are equal to static classes.
Sealed class A
{
Public int x=100;
}
Class Demo
{
Public static void Main()
{
A obj=new A();
Console.writeline(obj);
}
}
Sealed classes:
1)Can create instances, but cannot inherit
2)Can contain static as well as nonstatic members.
Static classes:
1)Can neither create their instances, nor inherit them
2)Can have static members only.
sealed class and sealed method
1. A class, which restricts inheritance for security reason is declared, sealed class.
2. Sealed class is the last class in the hierarchy.
3. Sealed class can be a derived class but can't be a base class.
4. A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit.
Practical demonstration of sealed class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_class
{
class Program
{
public sealed class BaseClass
{
public void Display()
{
Console.WriteLine("This is a sealed class which can’t be further inherited");
}
}
public class Derived : BaseClass
{
// this Derived class can’t inherit BaseClass because it is sealed
}
static void Main(string[] args)
{
BaseClass obj = newBaseClass();
obj.Display();
Console.ReadLine();
}
}
}
sealed method
Sealed method is used to define the overriding level of a virtual method.
Sealed keyword is always used with override keyword.
Practical demonstration of sealed method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_method
{
class Program
{
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Virtual method");
}
}
publicclass DerivedClass: BaseClass
{
// Now the display method have been sealed and can’t be overridden
public overridesealed voidDisplay()
{
Console.WriteLine("Sealed method");
}
}
//public class ThirdClass : DerivedClass
//{
// public override void Display()
// {
// Console.WriteLine("Here we try again to override display method which is not possible and will give error");
// }
//}
static void Main(string[] args)
{
DerivedClass ob1 = newDerivedClass();
ob1.Display();
Console.ReadLine();
}
}
}
No comments:
Post a Comment
Thank you for visiting my blog