MST

星途 面试题库

面试题:Ruby方法别名与重定义:复杂场景

假设你有一个Ruby类,其中包含多个实例方法和类方法。在类的继承体系中,子类重定义了父类的一个实例方法,同时父类的该方法有一个别名。当子类调用这个别名时,会发生什么情况?请详细说明原理,并给出代码示例来验证。
38.3万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
  1. 原理说明
    • 在Ruby中,当子类重定义了父类的一个实例方法,并且父类该方法有别名时,子类调用这个别名会调用到父类被别名的方法,而不是子类重定义的方法。这是因为别名是在定义别名时基于当时的方法绑定,别名会一直指向原来定义的方法,不受子类重定义的影响。
  2. 代码示例
class Parent
  def original_method
    puts "This is the original method in Parent"
  end
  alias alternative_method original_method
end

class Child < Parent
  def original_method
    puts "This is the overridden method in Child"
  end
end

child = Child.new
child.alternative_method

在上述代码中,Child类继承自Parent类并重定义了original_methodParent类中有original_method的别名alternative_method。当child.alternative_method被调用时,输出的是This is the original method in Parent,说明调用的是父类Parentoriginal_method方法,而不是子类Child重定义的original_method