Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent an inherited virtual method from being overridden in subclasses?

Tags:

I have some classes layed out like this

class A {     public virtual void Render()     {     } } class B : A {     public override void Render()     {         // Prepare the object for rendering         SpecialRender();         // Do some cleanup     }      protected virtual void SpecialRender()     {     } } class C : B {     protected override void SpecialRender()     {         // Do some cool stuff     } } 

Is it possible to prevent the C class from overriding the Render method, without breaking the following code?

A obj = new C(); obj.Render();       // calls B.Render -> c.SpecialRender 
like image 418
TrolleFar Avatar asked Sep 04 '08 11:09

TrolleFar


People also ask

Can you allow class to be inherited but prevent the method from being overridden?

Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.

Can you allow class to be inherited but prevent from being over ridden in Java?

No. Constructors in Java cannot be overridden because they are not inherited.

Is it possible to avoid a virtual method from getting overridden in C++?

In C++, there's no way to forbid it, it's just that by definition of "override", only virtual functions can be "overridden".

Does a virtual method have to be overridden?

When the method is declared as virtual in a base class, and the same definition exists in a derived class, there is no need for override, but a different definition will only work if the method is overridden in the derived class. Two important rules: By default, methods are non-virtual, and they cannot be overridden.


2 Answers

You can seal individual methods to prevent them from being overridable:

public sealed override void Render() {     // Prepare the object for rendering             SpecialRender();     // Do some cleanup     } 
like image 150
Matt Hamilton Avatar answered Sep 26 '22 08:09

Matt Hamilton


Yes, you can use the sealed keyword in the B class's implementation of Render:

class B : A {     public sealed override void Render()     {         // Prepare the object for rendering         SpecialRender();         // Do some cleanup     }      protected virtual void SpecialRender()     {     } } 
like image 38
Ian Nelson Avatar answered Sep 25 '22 08:09

Ian Nelson