VB.NET: Overloading, shadowing and overriding

Overloading: When two methods have the same name, return type and different arguments (in type or quantity), we say they are overloaded. If their arguments are the same, they must be in different classes to avoid a duplicate definition. If those classes are unrelated, it's alright and we're still in the overload case. But if one class inherits from another, either Shadowing or Overriding can ocurr.

Shadowing: This is what happens by default in VB.NET. Basically, the definition used when invoking is determined by the reference's type, not by the object's intrinsic type (the one with which it was created). In other word, there is no strict polymorphism/virtual mechanism. For example:

Imports System
 
Public Class Base
    Public Sub ShadowedSub()
        Console.WriteLine("ShadowedSub:Base")
    End Sub
End Class
 
Public Class Derived : Inherits Base
    Public Sub ShadowedSub()
        Console.WriteLine("ShadowedSub:Derived")
    End Sub
End Class
 
Public Class Test
   Public Shared Sub Main() 
       Dim derived As New Derived
       derived.ShadowedSub()          'Derived
       Dim upcastedDerived As Base = New Derived()
       upcastedDerived.ShadowedSub()  'Base! No polymorphism
   End Sub
End Class

Overriding: For polymorphism to work, we must declare the method as Overridable in Base, and as Overrides in Derived. I changed the method's name to OverridenSub just for simmetry, it was no necessary.

Imports System
 
Public Class Base
    Public Overridable Sub OverridenSub()
        Console.WriteLine("OverridenSub:Base")
    End Sub
End Class
 
Public Class Derived : Inherits Base
    Public Overrides Sub OverridenSub()
        Console.WriteLine("OverridenSub:Derived")
    End Sub
End Class
 
Public Class Test
   Public Shared Sub Main() 
       Dim derived As New Derived
       derived.OverridenSub()          'Derived
       Dim upcastedDerived As Base = New Derived()
       upcastedDerived.OverridenSub()  'Derived, as expected
   End Sub
End Class

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

C++/CLI: Convert a String to BSTR or some other nasty stuff