2
Reply

Can you create instances for sealed & static classes

17y
17k
0
Reply

    you can create instance of sealed class but not in static class.

    The below code will help you to distinguish the difference between a sealed class and a static class.You should use .net framework 2.0 to compile and run the code->

    namespace Static_Sealed

    {

    /* Static Class Declarartion */

    public static class statClass

    {

    public static int valA;

    public static int valB;

    public static int Add() { return (valA + valB); }

    }

    /* Sealed Class Declarartion */

    sealed class sealedClass

    {

    int a, b;

    sealedClass()

    {

    a = b = 0;

    }

    /*Method return the sum value of private variables a & b*/

    public int GetValue(int a, int b)

    {

    this.a = a;

    this.b = b;

    return (this.a + this.b);

    }

    [STAThread]

    static void Main(string[] args)

    {

    /* Create the instance of sealed class*/

    sealedClass objClass1 = new sealedClass();

    /*Calling the method of sealed class*/

    int Value1 = objClass1.GetValue(3, 4);

    /*Print the value*/

    Console.WriteLine("Sealed Class:The value is :" + Value1);

    /* Initialize the memeber of static class*/

    statClass.valA = 9;

    statClass.valB = 10;

    /*Calling the static method of static class*/

    int Value2 = statClass.Add();

    /*Print the value*/

    Console.WriteLine("Static Class:The value is :" + Value2);

    }

    }

    }

    You need the class name to access the members and methods of static class whereas in case of sealed class you can create the instance of it.