为什么ruby允许子类访问父类的私有方法?

时间:2022-05-27 23:05:57
class Main
    def say_hello
        puts "Hello"
    end

    private
        def say_hi
            puts "hi"
        end
end

class SubMain < Main
    def say_hello
        puts "Testing #{say_hi}"
    end

end

test = SubMain.new
test.say_hello()    

OUTPUT:

OUTPUT:

hi

Testing

测试

1 个解决方案

#1


10  

The difference is that in ruby you can call private methods in subclasses implicitly but not explicitly. Protected can be called both ways. As for why? I guess you would have to ask Matz.

区别在于,在ruby中,您可以隐式但不显式地调用子类中的私有方法。受保护可以双向调用。至于为什么?我想你不得不问Matz。

Example:

例:

class TestMain

  protected
  def say_bueno
    puts "bueno"
  end

  def say_ni_hao
    puts "ni hao"
  end

  private
  def say_hi
    puts "hi"
  end

  def say_bonjour
    puts "bonjour"
  end
end

class SubMain < TestMain
  def say_hellos
    # works - protected/implicit
    say_bonjour
    # works - protected/explicit
    self.say_ni_hao

    # works - private/implicit
    say_hi
    # fails - private/explicit
    self.say_bonjour
  end
end

test = SubMain.new
test.say_hellos()

#1


10  

The difference is that in ruby you can call private methods in subclasses implicitly but not explicitly. Protected can be called both ways. As for why? I guess you would have to ask Matz.

区别在于,在ruby中,您可以隐式但不显式地调用子类中的私有方法。受保护可以双向调用。至于为什么?我想你不得不问Matz。

Example:

例:

class TestMain

  protected
  def say_bueno
    puts "bueno"
  end

  def say_ni_hao
    puts "ni hao"
  end

  private
  def say_hi
    puts "hi"
  end

  def say_bonjour
    puts "bonjour"
  end
end

class SubMain < TestMain
  def say_hellos
    # works - protected/implicit
    say_bonjour
    # works - protected/explicit
    self.say_ni_hao

    # works - private/implicit
    say_hi
    # fails - private/explicit
    self.say_bonjour
  end
end

test = SubMain.new
test.say_hellos()