- 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.
- 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.
- 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?
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();