SEALED CLASS

Sometimes you may want to restrict derived class from overriding the virtual members. So for that, we have “sealed methods” which will restrict the derived class from overriding the implementation of the base class, Please

Sometimes you may want to restrict derived class from overriding the virtual members. So for that, we have “sealed methods” which will restrict the derived class from overriding the implementation of the base class, Please find the code below:

    public class Shape
    {
        public virtual double Area()
        {
            return 0;
        }
    }

    public class Circle: Shape
    {
        public double Radius { get; set; }

        public Circle()
        {
            Console.WriteLine("Circle Area");
            Console.WriteLine("Please enter the radius");
            Radius = Convert.ToDouble(Console.ReadLine());
        }

        public sealed override double Area() //you cannot inherit this method
        {
            return (3.14) * Math.Pow(Radius,2);
        }
    }

Sealed Class:

If we declare a class as sealed, we are taking away the inheritance feature from it. That is, the class can’ t be used as a base class and you can’t inherit it.

using System;

namespace PolymorphismUnderstanding
{
    public sealed class Shape
    {
        public double Area()
        {
            return 0;
        }
    }

    //Will throw an error as a shape is a sealed class
    public class Circle: Shape
    {
        public double Radius { get; set; }

        public Circle()
        {
            Console.WriteLine("Circle Area");
            Console.WriteLine("Please enter the radius");
            Radius = Convert.ToDouble(Console.ReadLine());
        }

        public double Area() 
        {
            return (3.14) * Math.Pow(Radius,2);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Shape s = new Shape();
            Console.WriteLine("Shape {0}", s.Area());

            Circle c = new Circle();
            Console.WriteLine("Circle {0}", c.Area());

            Shape ns = new Circle();
            Console.WriteLine("Circle {0}", ns.Area());

            Console.ReadKey();
        }
    }
}

Points:

  1. You can’t have virtual and abstrct members in an sealed class.

3 thoughts on “SEALED CLASS

Leave a Reply

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