Ruby之旅(四) 类的继承
来源:互联网 发布:java英文参考文献 编辑:程序博客网 时间:2024/05/20 20:21
Ruby之旅(四) 类的继承
直接上代码
Rectangle.rb
class Rectangle
attr_accessor :width
attr_accessor :height
def initialize(wdth, hgt)
@width = wdth
@height = hgt
end
def area()
return @width * @height
end
def +(addRectangle)
return area() + addRectangle.area()
end
end
attr_accessor :width
attr_accessor :height
def initialize(wdth, hgt)
@width = wdth
@height = hgt
end
def area()
return @width * @height
end
def +(addRectangle)
return area() + addRectangle.area()
end
end
Square.rb
require "Rectangle" # or require "Rectangle.rb"
class Square < Rectangle
def initialize(size)
@width = size
@height = size
end
end
s = Square.new(2)
puts s.area # output 4
class Square < Rectangle
def initialize(size)
@width = size
@height = size
end
end
s = Square.new(2)
puts s.area # output 4
我们可以看到Square继承了Rectangle类,并且拥有新的initalize方法。
这样 可以记住两个东西 一个是继承的符号是<,另一个是require方法可以包含另外的ruby源文件。
在ruby中,可以把方法的定义放在class外面,比如
def fell?()
puts "I fell fine."
end
fell?()
puts "I fell fine."
end
fell?()
这种写法好像是全局函数,其实并不是全局函数,而是给基类Object增加了一个fell?方法,因为任何类都从Object继承而来,所以这个时候任何类都将支持这个fell?方法。
0 0
- Ruby之旅(四) 类的继承
- Ruby之旅(六) 模块以及类的多继承
- RUBY学习之旅(四):JRUBY的hello world
- Ruby 学习四 (类、对象和变量二 类的继承和属性)
- ruby的继承
- Ruby的多继承
- [Java之四]继承的扩展
- javascript 的 继承(四) 之 原型式继承
- 我的RUBY之路--第三/四天 ruby on rails first blog / study ruby 基本语法 / Vim 基础快捷键
- Ruby on Rails 入门之:(14) Ruby中的继承
- Ruby学习之旅(三):Ruby的基本语法
- Ruby继承
- Ruby继承
- Ruby之旅(五) 类的封装性
- Ruby之旅--Ruby介绍与Java与Ruby的异同点
- python进阶四:类的继承
- java之 ------ 类的封装、继承和多态(四)
- Hibernate中的Entity类之间的继承关系之四TABLE_PER_CLASS
- 内存对齐
- CentOS 上 Jenkins 安装
- 最经典错误代码调试
- Solr对分词字段进行完全匹配加权的操作
- CCF计算机软件能力认证试题练习-图像旋转(Java参考答案学习记录)
- Ruby之旅(四) 类的继承
- 博客第一天
- Delphi指针的用法
- 使用kettle将文本文件中的数据导入数据库
- div+css实现左中右布局,解决右边一块掉落的问题
- 用new实现二位数组的几种方法
- 华为 4
- AngularJS(三)
- git rebase