What are the differences between “private”, “public”, and “protected methods”?

后端 未结 7 1796
栀梦
栀梦 2020-12-08 04:03

I\'m learning Ruby, and have come up to a point where I am confused.

The book I am using is talking about private, public, and protec

7条回答
  •  盖世英雄少女心
    2020-12-08 04:43

    Let me explain Private and protected methods work a little differently in Ruby than in most other programming languages. Suppose you have a class called Foo and a subclass SubFoo . In languages like Java, SubFoo has no access to any private methods defined by Foo . As seen in the Solution, Ruby provides no way to hide a class’s methods from its sub- classes. In this way, Ruby’s private works like Java’s protected.

    Suppose further that you have two instances of the Foo class, a and b. In languages like Java, a and b can call each other’s private methods. In Ruby, you need to use a protected method for that. This is the main difference between private and protected methods in Ruby.

    class Foo
      private
      def pri
        'hey I am private of Foo'
      end
    
      protected
      def prot
        'Hey I am protected of Foo'
      end
    end
    

    Now subclass of Foo

    class SubFoo < Foo
      def call_pri_of_foo
        pri
      end
    
      def call_prot_of_foo
        prot
      end
    end
    

    Now calling the accessors within SubFoo

     > sub_foo = SubFoo.new
     => # 
     > sub_foo.call_pri_of_foo
     => "hey I am private of Foo" 
     > sub_foo.call_prot_of_foo
     => "Hey I am protected of Foo"
    

    Up to here; there seem to be no difference

    next_sub_foo = SubFoo.new
     => #
    
    def next_sub_foo.access_private(child_of_sub_foo)
      child_of_sub_foo.pri
    end
    
    def next_sub_foo.access_protected(child_of_sub_foo)
      child_of_sub_foo.prot
    end
    

    Now calling the accessor

    > next_sub_foo.access_private(sub_foo)
    # => NoMethodError: private method `pri' called for #
    

    but it can access the protected methods of its siblings

    > next_sub_foo.access_protected(sub_foo)
    # => "Hey I am protected of Foo"
    

    You can also see @tenderlove's blog for more clear picture http://tenderlovemaking.com/2012/09/07/protected-methods-and-ruby-2-0.html

提交回复
热议问题