PART I
C h a p t e r 1 1 :
I n h e r i t a n c e
295
PART IPART I
class Derived2 : Base {
// Override Who() again in another derived class.
public override void Who() {
Console.WriteLine("Who() in Derived2");
}
}
class OverrideDemo {
static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base class reference
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who();
}
}
The output from the program is shown here:
Who() in Base
Who() in Derived1
Who() in Derived2
This program creates a base class called
Base
and two derived classes, called
Derived1
and
Derived2
.
Base
declares a method called
Who( )
, and the derived classes override it.
Inside the
Main( )
method, objects of type
Base
,
Derived1
, and
Derived2
are declared. Also,
a reference of type
Base
, called
baseRef
, is declared. The program then assigns a reference
to each type of object to
baseRef
and uses that reference to call
Who( )
. As the output
shows, the version of
Who( )
executed is determined by the type of object being referred to
at the time of the call, not by the class type of
baseRef
.
It is not necessary to override a virtual method. If a derived class does not provide its
own version of a virtual method, then the one in the base class is used. For example:
/* When a virtual method is not overridden,
the base class method is used. */
using System;
class Base {
// Create virtual method in the base class.
public virtual void Who() {
Console.WriteLine("Who() in Base");
}
}
www.freepdf-books.com
296
P a r t I :
T h e C # L a n g u a g e
class Derived1 : Base {
// Override Who() in a derived class.
public override void Who() {
Console.WriteLine("Who() in Derived1");
}
}
class Derived2 : Base {
// This class does not override Who().
}
class NoOverrideDemo {
static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base class reference
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who(); // calls Base's Who()
}
}
The output from this program is shown here:
Who() in Base
Who() in Derived1
Who() in Base
Here,
Derived2
does not override
Who( )
. Thus, when
Who( )
is called on a
Derived2
object, the
Who( )
in
Base
is executed.
In the case of a multilevel hierarchy, if a derived class does not override a virtual
method, then, while moving up the hierarchy, the first override of the method that is
encountered is the one executed. For example:
/* In a multilevel hierarchy, the first override of a virtual
method that is found while moving up the hierarchy is the
one executed. */
using System;
class Base {
// Create virtual method in the base class.
public virtual void Who() {
Console.WriteLine("Who() in Base");
www.freepdf-books.com
Do'stlaringiz bilan baham: |