Inheritance 对象声明为调用子类方法的父类
有人能解释一下这种行为吗?我有两门课,Inheritance 对象声明为调用子类方法的父类,inheritance,overriding,vb.net-2010,Inheritance,Overriding,Vb.net 2010,有人能解释一下这种行为吗?我有两门课,Foo和BarBar继承Foo并重写其GetVar函数: Public Class Foo Public myVar1 As Integer Public Overridable Function GetVar() As Integer Console.WriteLine("Foo.GetVar!()") Return myVar1 End Function End Class Public Cla
Foo
和Bar
Bar
继承Foo
并重写其GetVar
函数:
Public Class Foo
Public myVar1 As Integer
Public Overridable Function GetVar() As Integer
Console.WriteLine("Foo.GetVar!()")
Return myVar1
End Function
End Class
Public Class Bar
Inherits Foo
Public myVar2 As Integer
Public Overrides Function GetVar() As Integer
Console.WriteLine("Bar.GetVar!()")
Return MyBase.GetVar() + myVar2
End Function
End Class
在我的main()
模块中,发生以下情况:
Sub Main()
Dim myBar As New Bar
myBar.myVar1 = 2
myBar.myVar2 = 2
Dim myFoo As Foo
myFoo = myBar
Console.WriteLine(myFoo.GetVar())
Console.ReadKey()
End Sub
输出为:
Bar.GetVar()!
Foo.GetVar()!
4
这对我来说似乎很奇怪-
myFoo
被声明为类型为Foo
的对象,所以我认为调用myFoo.GetVar()
会调用Foo
的GetVar()
(输出2)实现,而不会显式地向下转换它,我认为myFoo
实际上是一个Bar
的事实会因为它的Foo
声明而“不可见”。为什么会发生这种情况?我明白了myFoo.getVar()
对myFoo
指向的对象调用getVar()
。虽然它不知道所说的对象是一个Bar
(并且不能访问Bar
专有的东西,比如myVar2
),但它仍然是一个Bar
,它在那里启动自己的getVar()
函数
我肯定这种行为有个名字,但我不记得了。有人要吗