站内搜索: 请输入搜索关键词
当前页面: 图书首页 > From Java To C# A Developers Guide

From Java To C# A Developers Guide

[ directory ] Previous Section Next Section

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.

    [ directory ] Previous Section Next Section