Shadowing using Shadows in Visual Basic.NET 2005 - Using Overloads instead of Shadows with overloaded parent methods in Visual Basic 2005
(Page 6 of 6 )
In the previous section, we observed that the keyword "shadows" completely hides based on name and not on signature. But what if we want to access all the methods from the parent through the child (without shadowing)? It is possible with "overloads!"
Let us redefine our classes as follows:
Public Class Parent
Public Sub DispMsg()
MessageBox.Show("From Parent")
End Sub
Public Sub DispMsg(ByVal Msg As String)
MessageBox.Show(Msg)
End Sub
End Class
Public Class Child2
Inherits Parent
Public Overloads Sub DispMsg()
MessageBox.Show("From child2")
End Sub
End Class
If you observe the "Child2," class, I replaced "shadows" with "overloads." This hides based on signature and not on name.
Let us test the classes using the following statements:
Dim objParent As New Parent
objParent.DispMsg()
objParent.DispMsg("Custom msg for parent")
We should not have any problem with the above, and indeed, it works successfully. Now let us proceed with the child object as follows:
Dim objChild As New Child2
Dim RefParent As Parent = objChild
objChild.DispMsg()
objChild.DispMsg("Custom msg for child2") 'works with overload
RefParent.DispMsg()
RefParent.DispMsg("Custom msg from ref object")
Now you can see that we are able to access all of the methods in the child and also in the parent (using a parent reference).
My previous article gave a good in depth understanding of "overrides" and "overloads" in Visual Basic 2005. This article completely discussed "shadows" together with "overloads" in Visual Basic 2005. In my next article, you will find information on "abstract" classes and "interfaces" together defining "polymorphism" using Visual Basic 2005.
I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |