1

In the program below, the child class method calls the parent class' private and protected methods.

class Parent  
  private
    def private_method
      'Private Method'
    end
  protected
    def protected_method
      'Protected Method'
    end
end

class Child < Parent
  def get_parent_name
    puts private_name
    puts protected_method
    puts Parent.new.protected_method
    puts Parent.new.private_method    #Throws an error
  end
end

obj = Child.new
obj.get_parent_name

The line

puts Parent.new.private_method    #Throws an error

throws an error. The difference I got is that a private method cannot be accessed using explicit receiver, but a protected method can. If this is the only difference between the private and protected methods, and both can be called in sub classes, then what is the use of these methods compared to other languages like java?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    similar question http://stackoverflow.com/questions/3534449/why-does-ruby-have-both-private-and-protected-methods – Alireza Oct 20 '14 at 12:05
  • My question is what is the use of private and protected methods if only the difference is of instance? –  Oct 20 '14 at 12:10
  • You are saying both protected and private methods can be called in sub classes, but in your example calling a private method of the parent in the subclass throws an error. that's the purpose of private and protected. Protected access is used when objects need to access the internal state of other objects of the same class, but not private methods – Alireza Oct 20 '14 at 12:34
  • Can you please give an example as I didn't get your answer –  Oct 20 '14 at 12:48
  • This link provides a good explanation with comparison to other languages and providing examples: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility – Alireza Oct 20 '14 at 15:16

0 Answers0