Information Technology Reference
In-Depth Information
Overriding a Method Marked override
Overriding methods can occur between any levels of inheritance.
When you use a reference to the base class part of an object to call an overridden
method, the method call is passed up the derivation hierarchy for execution, to the
most-derived
version of the method marked as
override
.
If there are other declarations of the method at higher levels of derivation, which are not
marked as
override
—they are not invoked.
For example, the following code shows three classes that form an inheritance hierarchy—
MyBaseClass
,
MyDerivedClass
, and
SecondDerived
. All three classes contain a method named
Print
, with the same signature. In
MyBaseClass
,
Print
is labeled
virtual
. In
MyDerivedClass
, it
is labeled
override
. In class
SecondDerived
, you can declare method
Print
with either
override
or
new
. Let's look at what happens in each case.
class MyBaseClass // Base class
{
virtual public void Print()
{ Console.WriteLine("This is the base class."); }
}
class MyDerivedClass : MyBaseClass // Derived class
{
override public void Print()
{ Console.WriteLine("This is the derived class."); }
}
class SecondDerived : MyDerivedClass // Most-derived class
{
... // Given in the following pages
}
Case 1—Declaring Print with override
If you declare the
Print
method of
SecondDerived
as
override
, then it will override
both the less-
derived versions
of the method, as shown in Figure 7-9. If a reference to the base class is used to
call
Print
, it gets passed all the way up the chain to the implementation in class
SecondDerived
.