Summary of differences between the access controllers public, private, and protected in ruby

Source: Internet
Author: User

Focus on private and protected

Public

The default value is public, which can be accessed globally.

Private

C ++, "private" indicates "private to this class", but Ruby prefers "private to this instance ".
In C ++, As long as class A can access Class A, it can access the private method of the object of Class.
Ruby, but not: You can only access the private method of this object in your object instance.
Because the ruby principle is "private means you cannot specify the method receiver", the receiver can only be self, and self must be omitted!
Therefore, subclasses in Ruby can access the private method of the parent class. However, self. private_method is incorrect.

Protected

It can be accessed in this class or subclass and cannot be accessed in other classes.

Test code (public access, Code omitted)
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"  endendclass 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  endendclass C  def test    a = A.new    #a.protected_mth          #wrong    #a.private_mth            #wrong  endendA.new.testB.new.testC.new.test

Note: There is no package difference between Ruby access control and Java.
Classes in other packages only need to reference the target class, which is the same as the class access control rules in the same package.

Reference: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility

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.