MST
星途 面试题库

面试题:Visual Basic类的继承与多态在实例化中的体现

假设有一个基类`Animal`,包含方法`MakeSound`,然后有两个子类`Dog`和`Cat`继承自`Animal`并分别重写`MakeSound`方法。请用Visual Basic代码实现这个继承结构,并展示如何在实例化`Dog`和`Cat`对象时,正确调用它们各自重写后的`MakeSound`方法,同时阐述这种多态性在实际开发中的优势。
36.1万 热度难度
编程语言Visual Basic

知识考点

AI 面试

面试题答案

一键面试
' 定义基类Animal
Public Class Animal
    Public Overridable Sub MakeSound()
        Console.WriteLine("动物发出声音")
    End Sub
End Class

' 定义子类Dog继承自Animal
Public Class Dog
    Inherits Animal
    Public Overrides Sub MakeSound()
        Console.WriteLine("汪汪汪")
    End Sub
End Class

' 定义子类Cat继承自Animal
Public Class Cat
    Inherits Animal
    Public Overrides Sub MakeSound()
        Console.WriteLine("喵喵喵")
    End Sub
End Class

' 测试代码
Module Module1
    Sub Main()
        Dim dog As New Dog()
        Dim cat As New Cat()

        dog.MakeSound() '调用Dog重写后的MakeSound方法
        cat.MakeSound() '调用Cat重写后的MakeSound方法

        ' 使用基类类型的变量来测试多态性
        Dim animal1 As Animal = New Dog()
        Dim animal2 As Animal = New Cat()

        animal1.MakeSound() '根据实际对象类型调用Dog的MakeSound方法
        animal2.MakeSound() '根据实际对象类型调用Cat的MakeSound方法
    End Sub
End Module

多态性在实际开发中的优势:

  1. 提高代码的可维护性和可扩展性:当需要添加新的动物类型时,只需要创建新的子类并继承Animal基类,重写MakeSound方法即可,而不需要修改大量现有的代码。例如,如果要添加一个Bird类,只需定义Bird类继承自Animal并实现自己的MakeSound方法,在主程序中调用相关功能的代码无需改变。
  2. 增强代码的灵活性:通过使用基类类型的变量来引用不同子类的对象,可以编写通用的代码来处理不同类型的对象。如上述代码中用Animal类型变量animal1animal2分别引用DogCat对象,然后调用MakeSound方法,根据实际对象类型执行不同的行为。这样可以将相同的操作应用于多种不同类型的对象,使得代码更加灵活和通用。
  3. 实现接口统一:所有继承自Animal的子类都有统一的MakeSound方法接口,这使得在处理各种动物对象时可以采用一致的方式进行调用,便于系统的整体设计和代码管理。