Ruby_访问控制(public,protected,private)

=begin
class test
def def1
puts "public"
end
def def2
puts "private"
end
def def3
puts "protected"
end
def def0
def1
def2
def3
end
public :def1 ,:def0
private :def2
protected :def3
end
=begin
test.def1
test.def2
test.def3
test.def0
#=end
test = test.new
#test.def1
#test.def2
#test.def3
#test.def0
class test1 <test

end
test1 = test1.new
test1.def1
test1.def0

class song
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
end
end
#asong = song.new("hello","song",124)
#puts asong.inspect
#puts asong.to_s
class karaokesong < song
def initialize(name, artist, duration, lyrics)
super(name, artist, duration)
@lyrics = lyrics
end
end

asong = karaokesong.new("my way", "sinatra", 225, "and now, the...")
puts asong.inspect # "song: my way--sinatra (225)"
class test
def one
puts "私有"
end
def two
one
puts "共有"
end
protected : one
public : two
end
test = test.new
test.two

class person
def talk
puts " public :talk, 将调用speak"
speak
end

def speak
puts "protected:speak,将调用laugh"
laugh
end

def laugh
puts " private:laugh"
end

protected :speak
private :laugh
end
p1=person.new
p1.talk
#p1.speak 实例对象不能访问 protected 方法
#p1.laugh 实例对象不能访问 private 方法
class person
def speak
"protected:speak "
end

def laugh
" private:laugh"
end

protected :speak
private :laugh
end

class student < person

def uselaugh
puts laugh
end

def usespeak
puts speak
end

end

p2=student.new
p2.uselaugh
p2.usespeak

class person
def speak
"protected:speak "
end
def laugh
" private:laugh"
end
protected :speak
private :laugh
def uselaugh(another)
puts another.laugh
end
def usespeak(another)
puts another.speak
end
end
p1=person.new
p2=person.new

p2.usespeak(p1)
#p2.uselaugh(p1)
=end
class person
private #后面的方法设定为private
def talk
puts " already talk "
end
end

p1=person.new
p1.talk # private方法不能访问

class person
public :talk
end

p1.talk
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值