Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make child classes unable to override method implementation [duplicate]

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?

like image 854
J. Doe Avatar asked Apr 21 '16 21:04

J. Doe


1 Answers

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
}
like image 109
Xiaoy312 Avatar answered Oct 01 '22 06:10

Xiaoy312