1、类和对象Class and Object精选关于对象式语言精选本课程并不系统讲授Eiffel语言但应学会“欣赏”Eiffel 语言(比较“纯”)它首先是一个对象式程序设计语言但强调从分析到设计到实现的平滑过渡2摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来3摘要三个世界三个世界:面向对象的建模面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来精选4三个世界精选客观世界 DVD播放机What is reality?复杂性 认识的主观性 问题世界抽象!A mod
2、el of a subset of the reality DVD播放机计算机(软件)世界A model of a model of a subset of the reality52022-12-12Institute of Computer SoftwareNanjing University现实世界现实世界问题世界问题世界软件世界软件世界Reality抽象抽象精选6摘要精选三个世界:面向对象的建模面向对象原则面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来7面向对象原则精选Object OrientationEncapsulationAbst
3、ractionPolymorphismInheritance8面向对象原则精选Object OrientationEncapsulationAbstractionPolymorphismInheritance9回顾:抽象数据类型精选抽象数据类型(ADT):用数学方法定义对象集合和运算集合,仅通过运算的性质刻画数据对象,而独立于计算机中可能的表示方法ADT规约方法代数规范语法部分,公理部分ADT实现E1,E2,E310面向对象原则精选Object OrientationEncapsulationAbstractionPolymorphismInheritance11封装精选封装是把过程和数据包围
4、起来,对数据的访问只能通过已定义的界面。DVD播放机12精选封装lProfessor Clark needs to be able to teach four classes in the next semester.SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()Professor ClarkSetMaxLoad()Name:J ClarkEmployee ID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:4SetMaxLoad(4)13精选
5、封装信息/实现隐藏Deposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number Deposit()Withdraw()Transfer()14精选封装封装使得对象在抽象所界定的范围内保持相对的独立,从而保证对象设计和对象实施方法的可靠分离。设计者和使用者分离!封装可以防止由于程序模块之间的互相依赖性而导致程序“不稳定”不会因某个部分的修改而导致整个系统许多部分都发生改动。封装是相对的!不能也没有必要阻止编程人员去查看实施细节。15精选封装 vs.继承矛盾吗?No!封装性主要指的是对象的封装性,引入继承机制后,对象仍然是封
6、装地很好的实体,其它对象与它通信只能发送消息。相似性:共享代码!继承:静态共享代码封装:动态共享代码16精选模块化传统的模块划分方法:要求组成的子程序(模块)有实际意义和明确的某个功能功能分解和结构分解OO的模块划分目标:生成一组有助于降低系统开发费用的模块,通过模块划分所得到的模块应该能够保证可以独立的生成和修改,每个模块的结构应该足够简单17精选模块化与抽象和封装密切相关模块的划分是以抽象出来的对象的性质和功能为依据的模块是封装得以实现的技术保障Booch:“模块化是反映一个被分解成一组相关联的松散结合模块组成系统的一个特性。”模块化以模块为基础18精选模块与类型的统一模块是软件分解的单元
7、,是语法概念类型是某些动态对象的静态描述,是语义概念传统语言 模块与类型分离对象语言 模块与类型统一类型:类是抽象数据类型的实现模块:类是对象式程序的基本组成单元基于类的面向对象的语言机制的强有力之处在于“类”统一了类型和模块19面向对象原则精选Object OrientationEncapsulationAbstractionPolymorphismInheritance20精选层次性封装性帮助隐藏细节;模块化使结构更加有序,但仍然不够!层次性是对抽象的排序和定位类结构关系(“is a”)对象结构关系(“part of”)实现方式继承:子类,父类单继承,多继承聚合:拥有关系/组合关系21精选
8、继承单继承CheckingSavingsSuperclass(parent)SubclassesInheritance RelationshipAncestorDescendentsAccount-balance-name-number+withdraw()+createStatement()22精选继承多继承Use multiple inheritance only when needed and always with caution!FlyingThingAnimalHorseWolfBirdHelicopterAirplaneMultiple Inheritance23精选继承继承 作
9、为模块扩展机制,体现开闭原则开闭原则,较好地支持软件的复用。继承 作为类型特化机制,体现分类方法,更合理地支持子类型实现。继承也是多态和动态绑定机制的基础。24精选子类对父类的扩展与特化继承表达的是一种分类演绎的认识方法“To program is to understand.”特化:包含范围变小,行为特殊化扩展:增加新的操作重定义:改变行为25精选The Open-Closed Principle(OCP)动机:软件是变化的!开闭原则:“Closed for Modification;Open for Extension”对修改关闭,对扩展开放!Why OCP?-重用How OCP?-继承2
10、6The Open-Closed PrincipleModules should be open and closed.Definitions:Open module:May be extended.Closed module:Usable by clients.May be approved,baselined and(if program unit)compiled.The rationales are complementary:For closing a module(managers perspective):Clients need it now.For keeping modul
11、es open(developers perspective):One frequently overlooks aspects of the problem.精选27The Open-Closed Principle(1)精选ACEDB28The Open-Closed Principle(2)精选ACEDBFAGH I29The Open-Closed Principle(3)精选ACEDBFAGH I30精选Example31面向对象原则精选Object OrientationEncapsulationAbstractionPolymorphismInheritance32精选多态多态性
12、使指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。多态性允许每个对象以适合自身的方式去响应共同的消息多态性增强了软件的灵活性和重用性。33精选多态ShapeCircleTriangleSquaredraw()draw()draw()draw()public class Shapes public static Shape randShape()switch(int)(Math.random()*3)default:case 0:return new Circle();case 1:return new Squar
13、e();case 2:return new Triangle();public static void main(String args)Shape s=new Shape3;/向数组里添加类型 for(int i=0;i s.length;i+)si=randShape();/用多态的方法调用 for(int i=0;i=0end精选40类的构成类名继承关系成员术语分类精选41Abstract data type POINTx:POINT REALy:POINT REAL:POINT REAL:POINT REALClass POINT:Choose a representation(pol
14、ar,cartesian)In polar representation,and are attributes,x and y are routines.精选yx42A simple classclass POINT featurex,y:REAL-Point cartesian coordinatesmove(a,b:REAL)is-Move by a horizontally and by b vertically.dox:=x+ay:=y+bendscale(factor:REAL)is-Scale by factor.dox:=factor*xy:=factor*yend精选43Cla
15、ss POINT(contd)distance(p:POINT):REAL is-Distance to pdoResult:=sqrt(x p.x)2+(y p.y)2)endro:REAL is-Distance to origin(0,0)doResult:=sqrt(x2+y2)endtheta:REAL is-Angle to horizontal axisdoendend精选44术语A class is an implementation of an abstract data type.Instances of the class may be created at run-ti
16、me;they are objects.类的实例在运行时刻产生,他们是对象。Every object is an instance of a class.每个对象都是一个类的实例。Note:In a pure O-O language such as Eiffel and Smalltalk this is true even of basic objects such as integers etc.Not true in C+or Java where such values have special status.精选45术语A class is characterized by fea
17、tures.Features comprise attributes(representing data fields of instances of the class)and routines(operations on instances).Routines are subdivided into procedures(effect on the instance,no result)and functions(result,normally no effect).Every operation(routine or attribute call)is relative to a dis
18、tinguished object,the current instance of the class.精选46Feature categories by role精选CommandQueryFeatureProcedureAttributeFunctionNo resultReturns resultComputationMemory47Feature categories by implementation精选ProcedureAttributeFunctionRoutineReturns resultNo resultMemoryComputationFeature48Feature c
19、ategories精选CommandQueryFeatureProcedureAttributeFunctionNo resultReturns resultComputationMemoryRoutineReturns resultNo resultMemoryComputationFeature49Alternative terminologyAttributes are also called instance variables or data member.Routines are also called methods,subprograms,or subroutines.Feat
20、ure call applying a certain feature of a class to an instance of that class is also called passing a message to that object.The notion of feature is particularly important as it provides a single term to cover both attributes and routines.It is often desirable not to specify whether a feature is an
21、attribute or a routine as expressed by the Uniform Access principle.精选50回顾:Uniform Access 访问一致性原则客户应能以实现无关的方式访问模块的功能,不管这个功能是通过存储还是计算来实现的。Facilities managed by a module must be accessible to clients in the same way whether implemented by computation or storage.精选51Uniform Accessbalance=list_of_deposi
22、ts.total list_of_withdrawals.total精选list_of_depositslist_of_withdrawalsbalancelist_of_depositslist_of_withdrawals(A2)(A1)52Uniform access through feature callTo access a property of a point p1,the notation is the same regardless of the representation,e.g.p1.xwhich is applicable both in cartesian rep
23、resentation(x is an attribute)and in polar representation(x is a function without arguments).In the first case the feature call is a simple field access;in the second it causes a computation to be performed.There is no difference for clients(except possibly in terms of performance).精选53类的使用类的使用有两种形式
24、允引 (class A is a client of class B)继承 (class A is a descendant of class B)Client and supplier a:S in CFeature calla.some_feature or a.some_feature()or infix operatorsSingle target principle精选54Use of the class in a client(1/5)class GRAPHICS featurep,q:POINT-Graphic pointssome_routine is-Use p and q.
25、local u,v:REALdo-Creation instructionscreate pcreate qendend精选0.00.0p(POINT)0.00.0q(POINT)55Use of the class in a client(2/5)class GRAPHICS featurep,q:POINT-Graphic pointssome_routine is-Use p and q.local u,v:REALdo-Creation instructionscreate pcreate qp.move(4.0,-2.0)-Compare with Pascal,C,Ada:-Mov
26、e(p,4.0,-2.0)endend精选4.0-2.0p(POINT)0.00.0q(POINT)56Use of the class in a client(3/5)class GRAPHICS featurep,q:POINT-Graphic pointssome_routine is-Use p and q.local u,v:REALdo-Creation instructionscreate pcreate qp.move(4.0,-2.0)-Compare with Pascal,C,Ada:-Move(p,4.0,-2.0)p.scale(0.5)endend精选2.0-1.0
27、p(POINT)0.00.0q(POINT)57Use of the class in a client(4/5)class GRAPHICS featurep,q:POINT-Graphic pointssome_routine is-Use p and q.local u,v:REALdo-Creation instructionscreate pcreate qp.move(4.0,-2.0)-Compare with Pascal,C,Ada:-Move(p,4.0,-2.0)p.scale(0.5)u:=p.distance(q)v:=p.xp:=qendend精选2.0-1.0p(
28、POINT)0.00.0q(POINT)58Use of the class in a client(5/5)class GRAPHICS featurep,q:POINT-Graphic pointssome_routine is-Use p and q.local u,v:REALdo-Creation instructionscreate pcreate qp.move(4.0,-2.0)-Compare with Pascal,C,Ada:-Move(p,4.0,-2.0)p.scale(0.5)u:=p.distance(q)v:=p.xp:=qp.scale(-3.0)endend
29、精选2.0-1.0p(POINT)0.00.0q(POINT)59精选模块与类型的统一从模块的观点:Set of available services(features or methods).从类型的观点:Description of set of possible run-time objects(its instances).如何做到?Every object is an instance of some class.Connection:The services of the class,viewed as a module,are the operations applicable
30、to the instances of the class,viewed as a type.60Applying abstraction principlesPrivileges of a client C of a class A on an attribute attrib:Read access if attribute is exported.Assuming a1:AThen a1.attrib is an expression.精选CAa1:A61The privileges of a client精选SecretRead-onlyRead,restricted writeFul
31、l write62Applying abstraction principlesBeyond read access:full or restricted write,through exported procedures.Full write privileges:set_attribute procedure,e.g.set_temperature(u:REAL)is-Set temperature value to u.dotemperature:=uensuretemperature_set:temperature=uendClient will use e.g.x.set_tempe
32、rature(21.5).精选63Other uses of a setter procedureset_temperature(u:REAL)is-Set temperature value to u.requirenot_under_minimum:u=-273not_above_maximum:u=2000dotemperature:=uupdate_databaseensuretemperature_set:temperature=uend精选64Delphi/C#“properties”Allowx.temperature:=21.5if there is a“setter”:pri
33、vate int temperature_internal;public int temperatureget return temperature_internal;set temperature_internal=value;/.Other instructions;.精选65Information hiding精选class A featuref.g.feature NONEh.feature B,Cj.feature A,B,CkendIn clients,with the declaration a1:A,we have:a1.f,a1.g:valid in any client a
34、1.h:invalid anywhere(including in As own text).a1.j:valid only in B,C and their descendants(not valid in A!)a1.k:valid in B,C and their descendants,as well as in A and its descendants66Information hiding(contd)Information hiding only applies to use by clients,using dot notation or infix notation,as
35、with a1.f(“Qualified calls”).Unqualified calls(within the class itself)are not subject to information hiding:class Afeature NONE h is -Does something.do .endfeature f is -Use h.do .hendend 精选DVD播放机67摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象对象:运行时刻的结构:运行时刻的结构对象创建:从类到对象对象引用:对象串起来68对象:系统的运行结构对象:A run-time in
36、stance of some class.某对象O是某类C的(直接)实例O包含为C中定义的属性(数据成员)当前状态(O的fields)运行规律类定义的行为面向对象的软件系统运行时由一组对象构成。对象是对问题域对象,并进而对现实对象的实现,三种对象概念上的一致性与差异性 精选DVD播放机69对象有状态The state of an object is one of the possible conditions in which an object may exist.The state of an object normally changes over time.精选Name:J Clark
37、Employee ID:567138Date Hired:July 25,1991Status:TenuredDiscipline:FinanceMaximum Course Load:3 classesProfessor Clark70对象有行为Behavior determines how an object acts and reacts.The visible behavior of an object is modeled by the set of messages it can respond to(operations the object can perform).精选Sub
38、mitFinalGrades()AcceptCourseOffering()TakeSabbatical()SetMaxLoad()Name:J ClarkEmployee ID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:3Professor Clark71对象有标识Each object has a unique identity,even if the state is identical to that of another object.精选Professor“J Clark”teaches Bio
39、logyProfessor“J Clark”teaches Biology72对象需要合作Objects are useless unless they can collaborate together to solve a problem.Each object is responsible for its own behavior and status.No one object can carry out every responsibility on its own.How do objects interact with each other?They interact throug
40、h messages.精选73对象 vs.类A class is an abstract definition of an object.It defines the structure and behavior of each object in the class.It serves as a template for creating objects Objects are grouped into classes.An object is an instance of a class.精选Professor-name-employeeID:UniqueId-hireDate-statu
41、s-discipline-maxLoad+submitFinalGrade()+acceptCourseOffering()+setMaxLoad()+takeSabbatical()ObjectsProfessor SmithProfessor MellonFrom Real WorldabstractingClass:ProfessorTo computer WorldinstancingJ Clark:ProfessorObjects74摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建对象创建:从类到对象:从类到对象对象引用:对象串起来75对
42、象创建对象按需创建,显式创建。传统技术往往基于栈分配实体运行时刻对象动态结构多变,而难以根据程序文本预测Eiffel 的对象创建基本创建基本创建 初始化featureCreation procedures精选76Creating an objectWith the class POINT as given:my_point:POINT.create my_pointEffect of such a creation instruction:Allocate new object of the type declared for my_point.Initialize its fields to
43、 default values(0 for numbers,false for booleans,null for characters,void for references).Attach it to the instructions target,here my_point.精选77Specific creation proceduresclass POINT createmake_cartesian,make_polarfeature-Initializationmake_cartesian(a,b:REAL)is-Initialize to abscissa a,ordinate b
44、.dox:=ay:=bendmake_polar.feature.The rest as before.精选78If there is a creation clauseCreation instructions must be“creation calls”,such ascreate my_point.make_polar(1,Pi/2)精选79If there is no creation clauseAn absent creation clause,as inclass POINT-No creation clausefeature The rest as before endis
45、understood as one that would only list default_create,as if it had been writtenclass POINT createdefault_createfeature The rest as before endProcedure default_create is defined in ANY as doing nothing;any class can redefine it to provide proper default initializations.精选80Associated conventionThe no
46、tationcreate xis understood(if permitted)as an abbreviation forcreate x.default_create精选81To allow both formsTo make both forms valid:create my_pointas well ascreate my_point.make_polar(1,Pi/2)it suffices to make default_create(redefined or not)one of the creation procedures:class POINT createmake_c
47、artesian,make_polar,default_createfeature.The rest as before.精选82To prohibit instantiating a classclass NOT_CREATABLE create-Nothing here!feature.The rest as before.end精选83摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用对象引用:对象串起来:对象串起来84对象引用回顾C+和Java的相应机制Void Reference,clone,copy and compa
48、re对象引用的问题精选85Forms of assignment and copyReference assignment(a and b of reference types):b:=aObject duplication(shallow):c:=clone(a)Object duplication(deep):d:=deep_clone(a)Also:shallow field-by-field copy(no new object is created):e.copy(a)精选86Shallow and deep cloningInitial situation:Result of:b:
49、=ac:=clone(a)d:=deep_clone(a)“Almaviva”namelandlordloved_oneaO1“Figaro”O2“Susanna”O3b“Almaviva”O4c“Almaviva”namelandlordloved_oneO5“Figaro”O6“Susanna”O7d精选87精选An object is a machine88精选Abastracted objectbeforeafteritemindexput_rightstartforthModel:Price:Manufacture:Size:89精选An object has an interfac
50、ebeforeafteritemindexput_rightstartforth90精选An object has an implementationstartforthput_rightbeforeafteritemindex91精选Information hiddingstartforthput_rightbeforeafteritemindex92小结三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来精选93作业(本次作业不用提交)尝试学习用Eiffel语言写一些简单的面向对象程序。可从http:/ 亦可简单一些http