Interface Inheritance

 <  Day Day Up  >  

Unlike classes, interfaces support multiple inheritance. That is, a single interface can inherit from multiple base interfaces.

 Interface IDrawable   Sub Draw() End Interface Interface IMoveable   Sub Move(ByVal X As Integer, ByVal Y As Integer) End Interface Interface IShape   Inherits IDrawable, IMoveable End Interface 

In this situation, the derived interface IShape contains members from its two base interfaces, IDrawable and IMoveable . So the IShape interface contains two members: IShape.Draw and IShape.Move .

Because an interface can inherit from multiple base interfaces, it is possible for the same interface to show up multiple times in the base interfaces of an interface (although an interface still cannot derive from itself). In that case, the interface is inherited from only once, not multiple times. For example:

 Interface ISizeable   Sub GetSize(ByRef X As Integer, ByRef Y As Integer) End Interface Interface IDrawable   Inherits ISizeable   Sub Draw() End Interface Interface IMoveable   Inherits ISizeable   Sub Move(ByVal X As Integer, ByVal Y As Integer) End Interface Interface IShape   Inherits IDrawable, IMoveable End Interface 

The IShape interface inherits GetSize only once, even though it derives from ISize through two separate paths. Types that implement interfaces that inherit the same interface multiple times have to implement the interface only once, as well.

 Class Square   Implements IShape   Sub GetSize(ByRef X As Integer, ByRef Y As Integer) _     Implements IShape.GetSize     ...   End Sub   Sub Draw() Implements IShape.Draw     ...   End Sub   Sub Move(ByVal X As Integer, ByVal Y As Integer) _     Implements IShape.Move     ...   End Sub End Class 

If an interface inherits members with the same name from two separate, unrelated interfaces, the conflicting members cannot be used in the derived interface without casting to one of the base interfaces. This is because there is no way for the compiler to know which method is supposed to be called. For example:

 Interface IDrawable   Sub GetSize(ByRef X As Integer, ByRef Y As Integer)   Sub Draw() End Interface Interface IMoveable   Sub GetSize(ByRef X As Integer, ByRef Y As Integer)   Sub Move(ByVal X As Integer, ByVal Y As Integer) End Interface Interface IShape   Inherits IDrawable, IMoveable End Interface Module Test   Sub Main()     Dim Shape As IShape = New Square()     Dim X, Y As Integer     ' Error: GetSize is multiply inherited.     Shape.GetSize(X, Y)     ' OK: Calls IDrawable.GetSize     CType(Shape, IDrawable).GetSize(X, Y)   End Sub End Module 
 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net