Home > OS >  How is the below multilevel inheritance working in .Net5?
How is the below multilevel inheritance working in .Net5?

Time:11-07

  1. In Image section 1, the intermediate class ClassA inherits the ClassASuper but does not override the Display method rather it gets overridden in sub child ClassB and it seems it working as expected.
  2. In Image section 2, the intermediate class ClassA inherits the ClassASuper and does override Display method which further gets overridden in sub child ClassB also and it seems it is also working as expected.
  3. In Image section 3, the intermediate class ClassA inherits the ClassASuper and does hide the Display method, which further gets overridden in sub child ClassB and it seems it is contradicting. --> Can someone explain how this is working behind the scene?

enter image description here

CodePudding user response:

In Section3, the new Display method hides the one inherited from the base class. It is the starting point for a new inheritance hierarchy. In this respect it is not any different from a totally new method with another name. You could have written e.g.:

public virtual void NewDisplay()
{
   ...
}

and override this one in ClassA and ClassB.

Therefore, a variable of type ClassASuper does not see this new method, because it is not overriding or implementing the original method. Since ClassASuper.Display is not overridden, it does correctly display

Print from ClassASuper

If you want to use the new method, you must cast to ClassA (or ClassB):

((ClassA)classASuperA).Display();
((ClassA)classASuperB).Display();
  • Related