Let's say I have a base abstract class named Animal
which has a virtual method named Move
.
I create a child class named Mammal
which inherits from Animal and defines the Move
method.
I then create a child class of Mammal
named Rabbit
.
Here's the thing:
I do not want Rabbit
to be able to override the implementation of Move
which Mammal
has already defined (child classes of Mammal
must not change the definition of Move, which Mammal
defined).
Since Rabbit
inherits from Mammal
, is it possible to "unvirtualize" the Move
method in the Mammal
class in order to prevent inheriting classes from overriding the method definition in Mammal
?
sealed
When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.
You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
class Animal
{
public virtual void Move() { }
}
class Mammal : Animal
{
public sealed override void Move() { }
}
class Rabbit : Mammal
{
public override void Move() { } // error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With