还在分不清protected和private吗,本文一分钟讲懂ruby中protected和private区别

Ruby 为您提供了三个级别的实例方法保护,分别是 public、private 或 protected。

Public 方法: Public 方法可被任意对象调用。默认情况下,方法都是 public 的,除了 initialize 方法总是 private 的。

Private 方法: 不能从外部访问,但是可以在类里面(或子类)用类方法访问,不能被类的对象调用(比如self.fun);

Protected 方法: 不能从外部访问,但是可以在类里面(或子类)用类方法访问,能被类的对象调用(比如self.fun),这里的调用只针对在类里面;

NOTE:private个protected都不能从外部访问,也就是不能实例化一个类,然后用类点函数来访问!

代码演示:pub.rb

  class Student
  Version = 2
  @@student_counts = 0
  attr_accessor :name, :no, :sex
  def initialize(name, no, sex)
    @name = name
    @no = no
    @sex = sex
  end

  def self.clazz_fun
    puts "This is a class method"
  end

  class << self
    def clazz_cun_2
      puts "This is a class method which the second way to write"
    end 

    def clazz_fun_3
      puts "This is a class method which the third way to write"
    end 
  end 

  def pub_fun
    puts "This is the common way #{@name}, #{self.no}, #{@sex}"
    pro_fun
    puts "the protected way can be called in this common way"
    pri_fun
    puts "the privated way can be called in this common way"
  end 

  public :pub_fun

  def pro_fun
    puts "This is a procted way"
  end 
  
  protected :pro_fun

  def pri_fun
    puts "This is a privated way"
  end

  private :pri_fun

end

Student.clazz_fun
s = Student.new("young", 24, "hanzi")
s.pub_fun

puts "---------------------------"

class Student
  def test
    self.pro_fun
    self.pub_fun
    # self.pri_fun   ERROR: pub.rb:60:in `test': private method `pri_fun' called for #<Student:0x00007f45990838c0 @name="young", @no=24, @sex="hanzi"> (NoMethodError) Did you mean?  pro_fun

  end
end

s.test

puts "+++++++++++++++++++++++++++++"

class MiddleStudent < Student
  def sub_fun
    pub_fun
    pro_fun
    pri_fun
    puts "1111111111111111111111"
    self.pub_fun
    self.pro_fun
    # self.pri_fun   ERROR: pub.rb:76:in `sub_fun': private method `pri_fun' called for #<MiddleStudent:0x00007f71c8bc64e8> (NoMethodError) Did you mean?  pro_fun

  end
end

MiddleStudent.clazz_fun
ms = MiddleStudent.new("yooy", 10, "girl")
ms.sub_fun


执行ruby pub.rb

结果:
在这里插入图片描述
分析结果:

在59行,我们可以看到,直接self.pri_fun,会报错,是因为:虽然这里依然是在类里面,但是self.就代表这是类的对象,我们上面说的是,private不能被类的对象调用,所以报错, 而58行的self.pub_fun没有报错,是因为在类里面,protect的方法可以被类的对象调用~

76行的报错也同理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白蒋博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值