MST

星途 面试题库

面试题:Ruby方法可见性在继承体系中的复杂表现

假设有一个Ruby类继承体系,父类中有不同可见性的方法,在子类中重写protected方法,并在子类的实例方法中调用父类的private方法(如果可行),请说明实现思路和可能遇到的问题及解决方案。
32.7万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 重写 protected 方法:在Ruby中,子类可以直接重写父类的 protected 方法。protected 方法在类及其子类的实例之间可以互相调用。
  2. 调用父类的 private 方法:通常情况下,Ruby中 private 方法不能通过显式的接收者调用。但可以通过在父类中定义一个中间的 protectedpublic 方法来间接调用 private 方法。

可能遇到的问题

  1. 直接调用 private 方法:如果在子类中尝试直接调用父类的 private 方法,例如 super.private_method,会引发 NoMethodError,因为 private 方法不能使用显式的接收者(如 super)来调用。

解决方案

  1. 间接调用:在父类中定义一个 protectedpublic 方法来调用 private 方法。例如:
class Parent
  def public_call_private
    private_method
  end
  private
  def private_method
    puts "This is a private method"
  end
end

class Child < Parent
  protected
  def protected_method
    puts "This is a overridden protected method"
  end

  def call_protected_and_private
    protected_method
    public_call_private
  end
end

child = Child.new
child.call_protected_and_private

在上述代码中,Parent 类定义了一个 public_call_private 方法,它调用了 private_methodChild 类重写了 protected 方法,并在 call_protected_and_private 方法中调用了重写的 protected 方法和通过父类的 public_call_private 间接调用了父类的 private 方法。