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