Sealed class - DotNet and DataBase

Wednesday, 1 August 2018

Sealed class





Sealed class
A class which restricts inheritance is called sealed class. When we created a class with the sealed keyword, we can't inherit that class in other class, only we can create the object to it.
The sealed class has to follow the below rules

1) It should be a derived class. Once a class is declared as sealed, the class members are also become sealed in nature, i.e, the members don't perform hiding & overriding.

Syntax
AccessSpecifier  sealed Classname
{

}

We can't inherit sealed class as below

The sealed class supports instance object creation but restrict inheritance.

Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SealedClass
{
    class Program
    {
        public void ccmethod1()
        {
            scClass1 sc = new scClass1();

        }
        static void Main(string[] args)
        {
            scClass1 sc = new scClass1();
            sc.scMethod1();
            Console.Read();
        }
    }
    sealed class scClass1
    {
        public void scMethod1()
        {
            Console.WriteLine("I'm a sealed member : scMethod1, under: scClass1 ");
        }
    }
}


Sealed method
A method which restricts hiding & overriding is called sealed method. But a sealed method should over ridden from some of the base class. If a class is having sealed method, the class should not be considered as a sealed method.

Declaration of a sealed method
public sealed override returnType methodname()
        {
            Statements
        }

Example
class baseClass1
    {
        public virtual void scMethod1()
        {
            Console.WriteLine("I'm a sealed member : scMethod1, under: scClass1 ");
        }
    }

    class baseClass2: baseClass1
    {
        public sealed override void scMethod1()
        {
            Console.WriteLine("I'm a sealed member : scMethod1, under: baseClass2 ");
        }
    }

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.