Make child classes unable to override method implementation

Say I have a base abstract class called Animal , which has a virtual method called Move .

I am creating a child class called Mammal that inherits from Animal and defines a Move method.

Then I create a child class Mammal called Rabbit .

Here's the thing:

I do not want Rabbit be able to override the implementation of Move that is already defined by Mammal (child classes of Mammal should not change the definition of Move that Mammal defined).

Since Rabbit inherits from Mammal , is it possible to β€œactivate” the Move method in the Mammal class to prevent classes from inheriting from overriding the method definition in Mammal ?

+5
source share
1 answer

sealed

When applied to a class, a sealed modifier prevents the inheritance of other classes. In the following example, class B inherits from class A, but no class can inherit from class B.

You can also use a hidden modifier for a method or property that overrides the virtual method or property in the base class. This allows you to derive classes 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 } 
+6
source

Source: https://habr.com/ru/post/1247663/


All Articles