Information Technology Reference
In-Depth Information
Methods
At first glance, implementing an interface seems to be the same as over-
riding a virtual function. You provide a definition for a member that has
been declared in another type. That first glance is very deceiving. Imple-
menting an interface is very different from overriding a virtual function.
Members declared in interfaces are not virtual—at least, not by default.
Derived classes cannot override an interface member implemented in a base
class. Interfaces can be explicitly implemented, which hides them from a
class's public interface. They are different concepts with different uses.
But you can implement interfaces in such a manner that derived classes
can modify your implementation. You just have to create hooks for derived
classes.
To i l l u s t r a t e t h e d i f f e r e n c e s , e x a m i n e a s i m p l e i n t e r f a c e a n d i m p l e m e n t a -
tion of it in one class:
interface
IMsg
{
void
Message();
}
public class
MyClass
:
IMsg
{
public void
Message()
{
Console
.WriteLine(
"MyClass"
);
}
}
The Message() method is part of MyClass's public interface. Message can
also be accessed through the IMsg point that is part of the MyClass type.
Now let's complicate the situation a little by adding a derived class:
public class
MyDerivedClass
:
MyClass
{
public void
Message()
{
Console
.WriteLine(
"MyDerivedClass"
);
}
}