Accessing base class element from derived class

  • Thread starter Thread starter sougata12
  • Start date Start date
S

sougata12

Guest
I was trying to see different ways i can access base class elements from the derived class. The first code that I wrote is shown below. It may be noted that the name Temp has been used multiple times: "Temp" is a variable in the base class, Temp() is a subroutine in the derived class. In this case I am getting an error in the statement Console.WriteLine("Through Sub TEMP() in Class TWO: var = {0}", temp). In other words, I am not able to access the variable temp in the base class from the derived class.

Module Module1
Sub Main()
Dim instance_two As New two()
instance_two.Temp()
Console.ReadLine()
End Sub
End Module

Class one
Public temp As Integer = 42
'Trying to access this
End Class

Class two : Inherits one
Shadows Sub Temp()
Console.WriteLine("Through Sub TEMP() in Class TWO: var = {0}", temp)
'Error comes in above line under Temp.
End Sub
End Class

However when we change the name of the subroutine temp() in the derived class to something else, we are able to access the variable temp in the base class using the console.writeline statement in the derived class. See below:

Module Module1
Sub Main()
Dim instance_two As New two()
instance_two.Test() 'instance_two.Temp() changed to instance_two.Test()
Console.ReadLine()
End Sub
End Module
Class one
Public temp As Integer = 42
End Class
Class two : Inherits one
Sub Test() 'Temp() changed to Test()
Console.WriteLine("Through Sub TEMP() in Class TWO: var = {0}", temp)
'Now the above statement works fine. Output is 42 as desired
End Sub
End Class


Can someone please explain what is happening? Why is the compiler not able to access the variable temp = 42 in the first case and why things work fine when the name of the subroutine is changed?


Sougata Ghosh

Continue reading...
 
Back
Top