码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-19 13:32:49      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

=begin
Public 方法: Public 方法可被任意对象调用。默认情况下,方法都是 public 的,initialize 方法总是 private 的。
Protected 方法: Protected 方法只能被类及其子类的对象调用。访问也只能在类及其子类内部进行。
Private 方法: Private 方法不能被明确的接受者调用,其接受者只能是self,所以只能在当前对象的上下文中被调用
=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

 

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

标签:

原文地址:http://www.cnblogs.com/stellar/p/5684162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!