I am trying to understand multiple inheritance in interfaces. I have borrowed the code from the following website and converted it to VB.NET: http://www.oodesign.com/interface-segregation-principle.html
Public Interface IWorker
Inherits IFeedable, IWorkable
End Interface
Public Interface IWorkable
Sub work()
End Interface
Public Interface IFeedable
Sub eat()
End Interface
Public Class Worker
Implements IWorkable, IFeedable
Public Sub eat() Implements IFeedable.eat
End Sub
Public Sub work() Implements IWorkable.work
End Sub
End Class
Public Class Robot
Implements IWorkable
Public Sub work() Implements IWorkable.work
End Sub
End Class
Class Manager
Dim worker As IWorkable
Public Sub setWorker(ByVal w As IWorkable)
worker = w
End Sub
Public Sub manage()
worker.work()
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim Test As New Manager
Dim IWorkerRobot As IWorkable = New Robot
Test.setWorker(IWorkerRobot)
Catch ex As Exception
'I won't absorb the exception.
End Try
End Sub
End Class
I don’t understand what the point of the IWorker interface is now that there is a IWorkable and IFeedable interface (IWorker extends IFeedable and IWorkable). I realize that this it will have something to do with polymorphism but I am not sure.
It depends entirely on the code that’s using the object. That’s where it actually gets “polymorphed.”
IWorkablethen it will be used as anIWorkable.IFeedablethen it will be used as anIFeedable.IWorker. (To that end, yourWorkerclass should probably implement all three interfaces so it can be used as anIWorker.)The main point is that none of these blocks of code need to know or care whether they’re operating on a
Workeror aRobotor aManager.In generalized code (see the Strategy Pattern as a common example) polymorphism comes into play by interpreting an object as another type. If that object can polymorph into that type (through interfaces, inheritance, any form of object abstraction) then it can be used as such. The same object in memory can be interpreted as any time that it implements.