Information Technology Reference
In-Depth Information
The following code implements this case. Notice the code in the last two lines of
method
Main
.
The first of the two statements calls the
Print
method by using a reference to the most-
derived class—
SecondDerived
. This is not calling through a reference to the base class
portion, so it will call the method implemented in
SecondDerived
.
The second statement, however, calls the
Print
method by using a reference to the base
class—
MyBaseClass
.
class SecondDerived : MyDerivedClass {
override public void Print() {
↑
Console.WriteLine("This is the second derived class.");
}
}
class Program {
static void Main()
{
SecondDerived derived = new SecondDerived(); // Use SecondDerived.
MyBaseClass mybc = (MyBaseClass)derived; // Use MyBaseClass.
derived.Print();
mybc.Print();
}
}
The result is that regardless of whether
Print
is called through the derived class or the base
class, the method in the most-derived class is called. When called through the base class, it is
passed up the inheritance hierarchy. This code produces the following output:
This is the second derived class.
This is the second derived class.
Figure 7-9.
Execution is passed to the top of the chain of multiple levels of override.