Sealed,static and abstract class difference.

Sealed Class

A sealed class cannot be used as a base 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.

 

We can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables to allow classes to derive from class and prevent them from overriding specific virtual methods or properties.

class X

{

protected virtual void F() { Console.WriteLine(“X.F”); }

protected virtual void F2() { Console.WriteLine(“X.F2”); }

}

class Y : X

{

sealed protected override void F() { Console.WriteLine(“Y.F”); }

protected override void F2() { Console.WriteLine(“Y.F2”); }

}

class Z : Y

{

// Attempting to override F causes compiler error CS0239.

// protected override void F() { Console.WriteLine(“C.F”); }

 

// Overriding F2 is allowed.

protected override void F2() { Console.WriteLine(“Z.F2”); }

}

It is an error to use the abstract modifier with a sealed class, because an abstract class must be inherited by a class that provides an implementation of the abstract methods or properties.

When applied to a method or property, the sealed modifier must always be used with override.

Because structs are implicitly sealed, they cannot be inherited.

Static Class

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

 

Difference between static and sealed class.

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.

 Difference between abstract and sealed

The abstract keyword enables to create classes and class members that are incomplete and must be implemented in a derived class.

The sealed keyword enables to prevent the inheritance of a class or certain class members that were previously marked virtual.

class Animal

{

public void Eat() { Console.WriteLine(“Eating.”); }

public override string ToString()

{

return “I am an animal.”;

}

}

sealed class fr:Animal

{

public static void hj(int h) { h = 5; }

}

 

static class fr1:Animal—–Error

{

public static void hj(int h) { h = 5; }

}

Leave a Reply