Tuesday 28 April 2015

What is Sealed class in asp.net c# ?

Sealed Class :-


Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

Sorce code example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
using System.Data;

namespace ConsoleDemoApp
{
    class MySealed
    {
        /* program to implement Sealed class in c# */

      
           static void Main(string[] args)
            {
                SealedClass sealedCls = new SealedClass();
                Console.WriteLine("Please enter first number");
                int a = int.Parse(Console.ReadLine());
                Console.WriteLine("Please enter second number");
                int b = int.Parse(Console.ReadLine());
                int total = sealedCls.Add(a, b);
                Console.WriteLine("Total = " + total.ToString());
                Console.ReadKey();
            }

      
    }

    // Sealed class example
     sealed class SealedClass
     {
        public int Add(int x, int y)
        {
            return x + y;
        }
     }
 }

Potput














Sealed Method :

When an instance method declaration includes a sealed modifier, that method is said to be a sealed method. A sealed method overrides an inherited virtual method with the same signature. A sealed method shall also be marked with the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method.

Source code

class AA
    {
        public virtual void First()
        {
            Console.WriteLine("First Class AA");
        }
        public virtual void Second()
        {
            Console.WriteLine("Second Class AA");
        }
    }
    class BB : AA
    {
        public sealed override void First()
        {
            Console.WriteLine("First Class BB");
        }
        public override void Second()
        {
            Console.WriteLine("Second Class BB");
        }
    }
    class CC : BB
    {
        public override void Second()
        {
            Console.WriteLine("First Class CC");
        }
    }


Note :-

Below method can be further override

public sealed override void First()
        {
            Console.WriteLine("First Class BB");
        }
        

    

No comments:

Post a Comment