Information Technology Reference
In-Depth Information
IMsg m = d as IMsg ;
m.Message(); // prints "MyDerivedClass"
MyClass b = d;
b.Message(); // prints "MyClass"
One way to fix this problem is to modify the base class, declaring that the
interface methods should be virtual:
public class MyClass : IMsg
{
public virtual void Message()
{
Console .WriteLine( "MyClass" );
}
}
public class MyDerivedClass : MyClass
{
public override void Message()
{
Console .WriteLine( "MyDerivedClass" );
}
}
MyDerivedClass—and all classes derived from MyClass—can declare their
own methods for Message(). The overridden version will be called every
time: through the MyDerivedClass reference, through the IMsg reference,
and through the MyClass reference.
If you dislike the concept of impure virtual functions, just make one small
change to the definition of MyClass:
public abstract class MyClass : IMsg
{
public abstract void Message();
}
Ye s , y o u c a n i m p l e m e n t a n i n t e r f a c e w i t h o u t a c t u a l l y i m p l e m e n t i n g t h e
methods in that interface. By declaring abstract versions of the methods in
the interface, you declare that all types derived from your type must imple-
ment that interface. The IMsg interface is part of the declaration of
MyClass, but defining the methods is deferred to each derived class.
Search WWH ::




Custom Search