Question about overriding and shadowing

phicha

Well-known member
Joined
May 11, 2009
Messages
45
Programming Experience
Beginner
VB.NET:
Class A
    Public Overridable Sub F()
        Console.WriteLine("A.F")
    End Sub 
End Class 

Class B
    Inherits A

    Public Overrides Sub F()
        Console.WriteLine("B.F")
    End Sub 
End Class 

Class C
    Inherits B

    Public Shadows Overridable Sub F()
        Console.WriteLine("C.F")
    End Sub 
End Class 

Class D
    Inherits C

    Public Overrides Sub F()
        Console.WriteLine("D.F")
    End Sub 
End Class 

Module Test
    Sub Main()
        Dim d As New D()
        Dim a As A = d ' <-- how can this be ? i think suppose it is  dim a as a = new A not d
        Dim b As B = d
        Dim c As C = d
        a.F()
        b.F()
        c.F()
        d.F()
    End Sub 
End Module

and the result is
B.F <-- dont know why
B.F <-- dont know why
D.F <-- dont know why
D.F <-- ok i accept it


can some one please help me explain itu how does it work ?
thanks,
 
A few points of interest; You can contain an object in a variable of a descending type (inherits from), this is called type casting and does not change the object, only what type member you can see using that variable. So all these variables point to the same object, no conversion is taking place. When down-casting it is not necessary to use explicit casts CType/DirectCast. When using Shadows a new member is defined, this can only be seen when the object is cast as the type that define it or inherit it, but not from a base type. When overriding a new implementation is provided for an existing inherited member, even when cast to a base type the override is used. In this case A.F is the original method, B.F overrides it, C.F defines a new Shadow method, D.F overrides the C.F method. D object seen as both D and C will use the latest D.F override (if D.F didn't exist then the C.F would be used in both cases), D object seen as both B and A will use the latest B.F override, because the later new C.F shadow is not seen here.

Some relevant help pages:
Shadows
Overrides
Differences Between Shadowing and Overriding
Shadowing in Visual Basic
 
Back
Top