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’s 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 (and non-virtual
methods) are resolved at compile time—this 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 location—a technique known as inlining the code.
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’s 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 apps that use string
s can rely on the functionality of string
objects as specified in the Framework Class Library.
Attempting to declare a derived class of a sealed
class is a compilation error.