6.7. Sealed classes (Java final classes)

A sealed class is the C# version of a Java final class. Sealing classes prevent unintended or unauthorized subclassing. It also enables certain runtime optimizations by the underlying runtime environment.

Lines 7 – 8 in the program which follows declares a sealed class called Parent. Being sealed, no other class is allowed to subclass it, hence explaining the compilation error.

1: // Negative example
2: class Child:Parent{
3:   public static void Main(){
4:   }
5: }
6:
7: sealed class Parent{
8: }

Compilation error:

test.cs(2,7): error CS0509: 'Child' : cannot inherit from sealed class 'Parent'

Like Java:

  • Sealed classes cannot be derived from.

  • Abstract classes cannot be sealed. [13]

    [13] Abstract classes are meant to be subclassed, while sealed classes cannot be subclassed. So it makes sense that a class cannot be abstract and sealed. The same argument goes for methods – there is no such thing as an abstract sealed method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.234.188