sealed Methods and Classes

We saw in Section 10.4 that only methods declared virtual, override or abstract can be overridden in derived classes. A method declared sealed in a base class cannot be overridden in a derived class. Methods that are declared private are implicitly sealed, because it is impossible to override them in a derived class (though the derived class can declare a new method with the same signature as the private method in the base class). Methods that are declared static also are implicitly sealed, because static methods cannot be overridden either. A derived class method declared both override and sealed can override a base class method, but cannot be overridden in derived classes further down the inheritance hierarchy.

A sealed method's declaration can never change, so all derived classes use the same method implementation, and calls to sealed methods are resolved at compile timethis is known as static binding. Since the compiler knows that sealed methods cannot be overridden, it can often optimize code by removing calls to sealed methods and replacing them with the expanded code of their declarations at each method-call locationa technique known as inlining the code.

Performance Tip 11 1

The compiler can decide to inline a sealed method call and will do so for small, simple sealed methods. Inlining does not violate encapsulation or information hiding, but does improve performance because it eliminates the overhead of making a method call.

A class that is declared sealed cannot be a base class (i.e., a class cannot extend a sealed class). All methods in a sealed class are implicitly sealed. Class string is a sealed class. This class cannot be extended, so applications that use strings can rely on the functionality of string objects as specified in the FCL.

Common Programming Error 11 5

Attempting to declare a derived class of a sealed class is a compilation error.

Software Engineering Observation 11 5

In the FCL, the vast majority of classes are not declared sealed. This enables inheritance and polymorphismthe fundamental capabilities of object-oriented programming.

Case Study Creating and Using Interfaces

Категории