Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing the virtual and override in inheritance chain

Please note: This is a conceptual question and not related to production specific code.

Suppose we have Class A with virtual method GetBonus(int value)

Next, we derive a class from this called Class B. In this Class B we override the method GetBonus.

Next, we derive a class from Class B called Class C.

Now class C can also override the GetBonus method of class A.

Question:

  1. Whether Class C overrides the method definition of Class A or of the Class B?

  2. In Class C, How can the overriding of the method of Class A be prevented ?

  3. In Class C, How can the overriding of the method of Class B be prevented ?

I know that there is a SEALED keyword for sealing the virtual overridden methods. But above questions will help me clear my doubts.

like image 597
helloworld Avatar asked Feb 10 '23 06:02

helloworld


2 Answers

Questions 2 and 3 boil down to the same thing basically, and sealed is indeed the answer here.

Perhaps you asked it a bit vague, but you can only prevent overriding of virtual methods in derived classes. Not in the derived class itself. In the end, for both questions 2 and 3, you have only one option:

class A
{
    public virtual void GetBonus(int value) { }
}

class B : A
{
    public sealed override void GetBonus(int value) { } // We seal this method
}

class C : B
{
    public override void GetBonus(int value) // This line is invalid
      // because it cannot override the sealed member from class B.        
    {   }
}

This will prevent method GetBonus from getting overridden in derived classes.

This sample also answers question 1. It gives a compilation error because class C's override of GetBonus is attempting to override the version provided by class B and not the one provided by A. This is true because overriding the one from A would obviously work as it isn't sealed.

like image 89
pyrocumulus Avatar answered Feb 13 '23 03:02

pyrocumulus


according to https://msdn.microsoft.com/en-us/library/ms173149%28v=vs.110%29.aspx (take a look at picture) when you override a virtual method and then derived that class in another class you inherit overriden implementation

    class A
    {
        public virtual void GetBonus(int value)
        {
            //if you define this method as seald no one can override this
        }
    }

    class B:A
    {
        public override void GetBonus(int value)
        {

        }
    }

    class C:B
    {
        public override void GetBonus(int value)
        {
            //here we override implementation of class B
        }
    }
}
like image 33
Technovation Avatar answered Feb 13 '23 04:02

Technovation