Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ruby allow child classes access parent's private methods?

Tags:

oop

ruby

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:

hi

Testing

like image 976
CodeCrack Avatar asked May 18 '15 01:05

CodeCrack


People also ask

Can child class access private method of parent?

Since method overriding works on dynamic binding, it's not possible to override the private method in Java. private methods are not even visible to the Child class, they are only visible and accessible in the class on which they are declared.

Do child classes inherit private methods?

Private methods are inherited in sub class ,which means private methods are available in child class but they are not accessible from child class,because here we have to remember the concept of availability and accessibility.

Do private methods get inherited in Ruby?

The private methods in Ruby can also be inherited just like public and protected methods.


1 Answers

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.

Example:

class TestMain

  protected
  def say_hola
    puts "hola"
  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_hola
    # 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()
like image 86
errata Avatar answered Oct 23 '22 12:10

errata