面向对象(访问控制、继承、重写)

=begin
Public 方法: Public 方法可被任意对象调用。默认情况下,方法都是 public 的,initialize 方法总是 private 的。
Protected 方法: Protected 方法只能被类及其子类的对象调用。访问也只能在类及其子类内部进行。
Private 方法: Private 方法不能被明确的接受者调用,其接受者只能是self,所以只能在当前对象的上下文中被调用
=end
class Test
 def method1    #默认为公有方法
 …
 end

 protected  #保护方法
 def method2
 …
 end
 
 private  #私有方法
 def method3
 end

 public 
 def test_protected(arg) #arg是Test类的对象
  arg.method2   #正确,可以访问同类其他对象的保护方法
 end

 def test_private(arg) #arg是Test类的对象
  arg.method3  #错误,不能访问同类其他对象的私有方法
 end
end

obj1 = Test.new
obj2 = Test.new
  
obj1.test_protected(obj2)
obj1.test_private(obj2) 
=begin

1、Ruby语言,只有重写,没有其它语言具有的严格意义上的重载。
2、原因:
首先类似java的重载有三种情况,对应以下的3种
*由于缺省参数和可变参数,参数个数不同而产生的重载,在 Ruby中不再有效
*定义方法时,ruby不指定参数类型,因此第参数类型不同而产生的重载也不存在。
*第三种形式即上面两种情况的结合,故也不存在

=end
class Box
   # 构造器方法
   def initialize(w,h)
      @width, @height = w, h
   end
   # 实例方法
   def getArea
      @width * @height
   end
end

# 继承
class BigBox < Box

   # 添加一个新的实例方法
   def printArea
      @area = @width * @height
      puts "Big box area is : #@area"
   end
end

# 重写
class SmallBox < Box
    def getArea
        @area = @width * @height
        puts "重载后的面积:#{@area}"
    end
end

box = BigBox.new(10, 20)
box1 = SmallBox.new(2,3)
box.printArea
box1.getArea
原文地址:https://www.cnblogs.com/stellar/p/5684162.html