I read that inheritance should be used only if you want to use the overriding facility. Interfaces and composition should be used if you only use inheritance for code sharing. Have a look at the code below:
Public Class Animal
Public Overridable Sub Eat()
MsgBox("Animal Eat no arguement")
End Sub
End Class
Public Class Horse
Inherits Animal
Public Overrides Sub Eat()
MsgBox("Horse Eat no arguement")
End Sub
End Class
Horse inherits from Animal and overrides Eat. This is a valid use of inheritance based on what I read. Now say you add a Cat class and a Dog class that inherit from animnal. Now say that Horse; Cat and Dog use the Eat function from the Animal class (instead of overriding it) then this is an invalid use of inheritance based on what I read (interfaces shouod be used). Surely if you use interfaces i.e. IEatable to implement the Eat interface then Eat has to be written in every class, which minimizes reuseability and maintainability. What am I missing here?
Update
After reading the responses I believe I can do something like this:
Public Class Animal
Public Overridable Sub Eat()
MsgBox("Animal Eat no arguement")
End Sub
End Class
Public Class Fish
Inherits Animal
Implements ISwim
Private s1 As New Swim
Public Sub Swim() Implements ISwim.Swim
s1.Swim()
End Sub
End Class
Public Class Shark
Inherits Animal
Implements ISwim
Private s1 As New Swim
Public Sub Swim() Implements ISwim.Swim
s1.Swim()
End Sub
End Class
Public Class Elephant
End Class
Public Class Swim
Public Sub Swim()
MsgBox("Animal can swim")
End Sub
End Class
Public Interface ISwim
Sub Swim()
End Interface
In the above code, two of the three animals implement ISwim and use composition to provide an implementation of Swim. Is this a valid approach?
You would use inheritance for the implementation of
Eatif you can use the same code for all, or some, of the classes. If you need different implementations for some classes, you can make it virtual and use the implementation fromAnimalin any class that doesn’t specifically have a different implementation.You would use an interface if you have different implementations for all classes, or if you want to add the ability to only some of the clases. The
ISwiminterface would for example only be implemented by some animals.