Search code examples
rubyoop

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


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


Solution

  • 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()