a
is a variable that can hold an instance of
classA
- which includes any class which is derived from it.
So since
ClassC
is derived from
ClassB
, which in turn derives from
ClassA
when you create an instance of ClassC, you can assign it to
a
- but that doesn't change the instance, it just means you can only call
ClassA
methods on it.
When you call
Print
, the system looks for the highest method with a matching signature in the inheritance chain - which is the
ClassB
version which overrides the
ClassA
version because
ClassC
doesn't override
Print
from
ClassB
, it creates a new method of the same signature that "hides" the previous versions.
If you do this instead:
public static void Main()
{
classC c = new classC();
classA a = c;
Console.WriteLine(a.Print());
Console.WriteLine(c.Print());
}
You will get the
ClassB
and
ClassC
methods called because the first is looking for the
ClassA
version (overridden by
ClassB
)and the second is specifically looking for the
ClassC
method.