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.
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.
|
|
Case Study Creating and Using Interfaces
|