您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 薪酬管理 > Ruby语言程序设计_第3章_面向对象.
Ruby语言程序设计第三章:面向对象沃天宇woty@act.buaa.edu.cn2014-10-8内容提要•RubyO-O基本语法•Ruby面向对象讨论•模块和Mixin•函数式语言特征/程序块Rethinking:WhyObjectOriented?•与人类思维方式和手段相对应的面向对象程序设计语言,使得程序开发过程与人类的认知过程同步,通过对人类认识客观世界及事物发展过程的抽象,建立了规范化的分析设计方法,由此带来软件模块化特色突出、可读性好、易维护性强等一系列优点•面向对象的三个基本特征–封装——类(Class)–多态——重载(Overload)、覆盖(Override)–继承——extendsimplements•实现原理(C++)–虚函数表RubyO-O基本语法•基本类定义–类名必须是定义在全局空间上的常量•实例数据(成员变量)classFrogendclassfrogend#class/modulenamemustbeCONSTANTclassFrogdefname@nameenddefname=(value)@name=valueendendRubyO-O基本语法•属性访问器classFrogdefname@name#属性enddefname=(value)@name=value#属性endendfrog=Frog.newfrog.name='Tim'putsfrog.name#=“Tim”classFrogattr_reader:nameattr_writer:nameendclassFrogattr_accessor:nameendfrog=Frog.newfrog.name='Tim'putsfrog.name#=“Tim”符号RubyO-O基本语法•构造函数classFrogattr_accessor:namedefinitialize(name)@name=nameendendfrog=frog.new('Tim')putsfrog.name#=“Tim”小练习•给出程序运行结果classFrogattr_accessor:namedefinitialize(name)@name=nameenddefspeak@speak_english||=@name.size6@speak_english?Hi.Iam#{name},thetalkingfrog.:Ribbit.endendFrog.new('Leonard').speak#=______________alex=Frog.new('Alex')putsalex.speak#=_______________alex.name='Alexandra'putsalex.speak#=_______________alex.name='Al'putsalex.speak#=_______________类数据•@@开头的变量,在所有类实例之间共享classFrog@@number_instantiated=0definitialize(name)@name=name@@number_instantiated+=1enddefnumber_instantiated@@number_instantiatedendendfrog1=Frog.new('Tim')putsfrog1.number_instantiated#=1frog2=Frog.new('Tim')putsfrog2.number_instantiated#=2putsfrog1.number_instantiated#=2类方法classFrog@@number_instantiated=0definitialize(name)@name=name@@number_instantiated+=1enddefself.number_instantiated@@number_instantiatedendendfrog=Frog.new('Tim')putsFrog.number_instantiated#=1frog=Frog.new('Tim')putsFrog.number_instantiated#=2虚属性classArcattr_accessor:radiansdefdegrees@radians*180/Math::PIenddefdegrees=(degrees)@radians=degrees*Math::PI/180endendarc=Arc.newarc.degrees=180putsarc.radians#=3.14159265358979arc.radians=Math::PI/2putsarc.degrees#=90.0类继承•所有类都继承自ObjectclassAnimalattr_accessor:namedefinitialize(name)@name=nameendendclassFrogAnimalendputsFrog.new('Tim').nameKind_of?,is_a?,instance_of?classAattr_accessor:asdfendclassBAattr_accessor:bbbdefinitialize@asdf=asdfendenda=A.newb=B.new#B:0x42154cc@asdf=asdf“b.asdf#“asdf”b.kind_of?A#trueb.kind_of?B#truea.kind_of?B#falsea.is_a?A#_______a.is_a?B#_______b.is_a?A#_______b.is_a?B#_______a.instance_of?A#_______a.instance_of?B#_______b.instance_of?A#_______b.instance_of?B#_______方法重载(Override)•OverridevsOverloadclassAnimalattr_accessor:namedefinitialize(name)@name=nameenddefto_sAnimal:#{@name}endendclassFrogAnimaldefto_sFrog:#{@name}endendputsFrog.new('Tim')RubyOverload?puts(1,2,3)puts(A,B)puts(1,2,3,4)defsum(*number)total=0number.each{|x|total+=x}totalendputssum(1,2)putssum(1,2,3,4)putssum(*[1,2,3,4])putssum([1,2,3,4])#ERROR!调用超类方法•super关键字classAnimalattr_accessor:namedefinitialize(name)@name=nameenddefto_sAnimal:#{@name}endendclassFrogAnimaldefto_ssuper++Frog:#{@name}endendputsFrog.new('Tim')抽象方法•Ruby并无语言内建支持抽象方法定义classShape2DdefarearaiseNotImplementedError.new(Thisisanabstractmethod)endendShape2D.new.area#NotImplementedError:Thisisanabstractmethod私有方法•Ruby并无语言内建支持抽象方法定义classSecretNumberdefinitialize@secret=rand(20)endprivatedefsecret@secretendends=SecretNumber.news.secretRuby与面向对象•弱类型vs强类型classDuckdefquack'Quack'enddefswim'paddle…'endendclassGoosedefhonk'Honk'enddefswim'splash…'endend#如果ruby是强类型语言defmake_it_swim(Duckduck)duck.swimendmake_it_swim(Duck.new)#=“paddle…”make_it_swim(Goose.new)#TypeException#然而ruby是弱类型语言defmake_it_swim(duck)duck.swimendmake_it_swim(Duck.new)#=“paddle…”make_it_swim(Goose.new)#=“splash…”Ruby与面向对象•类是开放的classFixnumdefhoursself.*3600endaliashourhoursend1.hours#3600,可向现有的类动态添加方法!•上述做法甚至可以作用于对象实例!–a=String.new(“abc”)–defa.to_s;self+self;end–a.to_s#“abcabc”模块(Module)•描述一个类的某一方面的属性、功能•相关功能可以在不同类之间重用•特征–可以被include–可以包含实现、类方法–不能实例化,不能有initialize方法–动态联编–重名处理?(命名空间)•E.g.Math::PI模块(Module)•命名空间(Namespace)–E.g.Math::PIclassAdefcalMath::PIendendputsA.new.calclassAincludeMathdefcalPIendendputsA.new.cal模块(Module)moduleKickabledefkickputs“flying”endendclassFootballincludeKickableendf=Football.newf.kick#“flying”Mixin与多继承•C++:多继承;•Java:interface;•Ruby:Mixin方法覆盖顺序•子类定义的方法•(最后一个)Mixin的方法•父(祖先)类定义的方法•原则:–记住动态语言特征moduleKickabledefkickputsflyingendendmoduleAnotherKickabledefkickputsanotherflyingendendclassBalldefkickputskickingballendendclassFootballBallincludeKickableincludeAnotherKickableendf=Football.newf.kick#“anotherflying”关于面向对象•Mixin方法覆盖moduleZZPdefkickputsZZP'skickendendclassTestextendZZPdefkickputsTest'skickendendtest=Test.newtest.kickTest.kick关于面向对象•include与extend的区别moduleMaMA_VALUE=1defma_1putsitisma_1endendmoduleMbMB_VALUE=1defself.included(c)defc.mb_2putsitismb_2endenddefmb_1putsitismb_1endendc1=Ca.newc1.ma_1c2=Cb.newc2.mb_1Cb.ma_1Cb.mb_2putsMa::MA_VALUEputsCa::MA_VALUEputsMb::MB_VALUEputsCb::MB_VALUEclassCaincludeMaendclassCbextendMaincludeMbenditisma_1itismb_1itisma_1itismb_21111函数式语言特征/程序块•block:一小段代码•aBlock=lambda{|x|pu
本文标题:Ruby语言程序设计_第3章_面向对象.
链接地址:https://www.777doc.com/doc-2856256 .html