Inheritance and Polymorphism
19.1 Inheritance Basics
Public Class Animal
Public Property Name As String
Public Sub New(name As String)
Me.Name = name
End Sub
Public Overridable Function Speak() As String ' can be overridden
Return "..."
End Function
Public Function Describe() As String
Return $"{Name} says {Speak()}" ' polymorphic call
End Function
End Class
Public Class Dog
Inherits Animal
Public Property Breed As String
Public Sub New(name As String, breed As String)
MyBase.New(name) ' call the base constructor
Me.Breed = breed
End Sub
Public Overrides Function Speak() As String
Return "Woof"
End Function
End Class
Public Class Puppy
Inherits Dog
Public Sub New(name As String)
MyBase.New(name, "Unknown")
End Sub
Public NotOverridable Overrides Function Speak() As String ' stop further overriding
Return MyBase.Speak() & " (squeaky)"
End Function
End Class19.2 Polymorphism in Action
Dim animals As New List(Of Animal) From {
New Dog("Rex", "Labrador"),
New Puppy("Bit"),
New Animal("Generic")
}
For Each a In animals
Console.WriteLine(a.Describe()) ' calls the correct Speak() at runtime
Next
' Type checking and casting
For Each a In animals
If TypeOf a Is Dog Then
Dim d = DirectCast(a, Dog)
Console.WriteLine(d.Breed)
End If
Dim maybeDog = TryCast(a, Dog)
If maybeDog IsNot Nothing Then Console.WriteLine(maybeDog.Breed)
Next19.3 Inheritance Modifiers
Derive from a base class (single inheritance only) Can be overridden Overrides a base member Stops overriding further down Abstract: no body, must be overridden Abstract class: can't be instantiated Sealed: can't be inherited
Hides a base member by name (not polymorphic) Overload a base member with a different signature
19.4 Shadows vs Overrides
Public Class Base
Public Overridable Sub Show()
Console.WriteLine("Base")
End Sub
End Class
Public Class Derived
Inherits Base
Public Shadows Sub Show() ' hides Base.Show (no polymorphism)
Console.WriteLine("Derived")
End Sub
End Class
Dim b As Base = New Derived()
b.Show() ' "Base" (Shadows isn't virtual dispatch)19.5 The Object Base Class
All types inherit from System.Object: ToString(), Equals(), GetHashCode(), GetType(), Finalize(), MemberwiseClone().
Public Overrides Function Equals(obj As Object) As Boolean
Dim other = TryCast(obj, Product)
Return other IsNot Nothing AndAlso Name = other.Name AndAlso Price = other.Price
End Function
Public Overrides Function GetHashCode() As Integer
Return HashCode.Combine(Name, Price)
End Function19.6 Composition over Inheritance
Prefer "has-a" (holding other objects) over deep "is-a" hierarchies. Use interfaces for flexibility.