A summary of public, private, and protected differences in Ruby _ruby topics

Source: Internet
Author: User

Focus on private and protected

Public

The default is public, the global can be accessed, this does not explain

Private

C + +, "private" means "private to this class", but Ruby is the "private to this instance".
In C + +, for Class A, you can access the private method of A's object as long as you can access Class A.
Ruby, but not: You can only access this object's private method in the instance of your object.
Because Ruby's principle is "private means you cannot specify a method recipient," the receiver can only be self, and self must omit!
So the Ruby Neutron class can access the private method of the parent class. But Self.private_method is wrong.

Protected

can be accessed in this class or subclass, and not in other classes.

Test code (accessible by public, slightly code)

Class A
 def Test
  protected_mth
  private_mth
 
  self.protected_mth
  #self. private_mth   #wrong
 
  obj = b.new
  obj.protected_mth
  #obj. private_mth    #wrong
 end
 
 protected
 def protected_mth
  puts "#{self.class}-protected"
 end
 
 private
 def private_mth
  puts "#{ Self.class}-private "End"
 
class B < A
 def Test
  protected_mth
  private_mth
 
  self.protected_mth
  #self. private_mth   #wrong
 
  obj = b.new
  obj.protected_mth
  #obj. Private_ MTH    #wrong
 end
 
class C
 def test
  a = A.new
  #a. protected_mth     #wrong
  #a. private_mth      #wrong
 end
 
a.new.test
b.new.test
c.new.test


Note: Ruby's access control is different from Java, and there is no packet difference.
Classes in other packages simply reference the target class and are the same as the class access control rules under the target-like package.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.