Shadowing using Shadows in Visual Basic.NET 2005 - Accessing parent members when using Shadows in Visual Basic 2005
(Page 2 of 6 )
Let us consider two classes as follows:
Public Class Parent
Public x As Integer = 10
End Class
Public Class Child
Inherits Parent
Public Shadows x As Integer = 20 'default is shadows even if it is not defined
End Class
To test the above classes, I created two objects and accessed the fields as follows:
Dim objParent As New Parent
Dim objChild As New Child
MessageBox.Show("From Parent: " & objParent.x)
MessageBox.Show("From Child: " & objChild.x)
From the above, the first message gives "10" and the second gives "20."
Let us consider that I would like to access the parent member from the child object. It can be done using the following style of code:
Dim objChild As New Child
Dim RefParent As Parent = objChild
MessageBox.Show("From child with Parent Ref: " & RefParent.x)
In the above code "objChild" is a full-fledged instance and "RefParent" is simply a reference to another memory location (no new memory gets allocated for this). When inheritance is implemented, a child instance can be assigned to a parent reference; if necessary we can even type-cast it.
When we try to access a shadowed member in the child through a parent reference, the program doesn't consider shadowing any more. It concentrates only on parent members and thus the result would be "10."
Next: Using Shadows with properties in Visual Basic 2005 >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee