MST
星途 面试题库

面试题:Ruby 中多态性在方法重写方面的体现

在 Ruby 中,如何通过方法重写来实现多态性?请举例说明一个父类和至少两个子类,在子类中重写父类方法以展示多态行为,并解释代码运行机制。
49.3万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

1. 代码示例

# 定义父类Animal
class Animal
  def speak
    puts "动物发出声音"
  end
end

# 定义子类Dog,继承自Animal
class Dog < Animal
  def speak
    puts "汪汪汪"
  end
end

# 定义子类Cat,继承自Animal
class Cat < Animal
  def speak
    puts "喵喵喵"
  end
end

2. 多态行为展示

animals = [Animal.new, Dog.new, Cat.new]
animals.each do |animal|
  animal.speak
end

3. 代码运行机制解释

  • 继承DogCat 类继承自 Animal 类,这意味着它们拥有 Animal 类的属性和方法。
  • 方法重写DogCat 类分别重写了 Animal 类中的 speak 方法,提供了各自特有的实现。
  • 多态性:在 animals.each 循环中,animal 可以是 Animal 类及其子类的任何对象。当调用 animal.speak 时,Ruby 会根据 animal 实际的对象类型(运行时类型)来决定调用哪个 speak 方法。这就是多态性的体现,相同的方法调用,根据对象的不同类型,会产生不同的行为。