protect 继承_Ruby中类的进阶(继承,private, public, protect)

类中的public,protect,private

public method

class Point

def test

end

end

这样定义的test方法就是一个public方法可以在类内外使用

protected method

protected

protected 权限的函数只能在被本类或子类的上下文中调用,单可以使用other_object.function的形式。这个关键是可以调用本类的其他对象的protected函数

class Point

def test

end

protected :test

end

或者

class Point

protected

def test

end

end

实例:

# Now make 'test' protect

class B

protected :test_access

end

p A.new.test_access # 错误 private method 'test_access'

B.new.test # test access right

p B.new.test_other(B.new) # test access right

p B.new.test_other(A.new) # 错误 private method 'test_access'

只要在protected关键词之后那么就是protected

private

只能在本对象的实例中访问本对象的private方法,Ruby中private意为不能指定方法接收者,接收者只能是self,且self必须省略;

private权限的函数只能在本对象成员函数中访问到。也就是这个函数只是对这个对象的实现细节。

class A

private

def test_access

@instance_attribute = "instance_attribute"

return "test access right"

end

end

class B < A

def test

puts test_access

puts @instance_attribute

end

def test_other(a)

a.test.access

end

end

-------------------------

B.new.test # => test access right

# = > instance_attribute

A.new.test_access #错误test.rb:20: private method `test_access' called for #<0x3fd9064> (NoMethodError)0x3fd9064>

B.new.test_other(A.new) #错误test.rb:18: in `test_other': private method `test_access' called for #<0x4198850> (NoMethodError) from test.rb:240x4198850>

基本继承

直接进入主题吧,我们先定义一个类

class Point

def initialize(x, y)

# @x instance variable

# @@x class variable

# $x global variable

# x local variable

@x, @y = x, y

end

def first_quadrant?

x > 0 && y >0

end

end

这里我们创建一个新的类继承原来的类

class Point3D << Point

def initialize(x, y, z)

@x, @y, @z = x, y, z

end

end

但是我们可以使用super方法

class Point3D << Point

def initialize(x, y, z)

super(x, y)

@z = z

end

end

继承了父类中的方法,不用写重复的代码了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值