




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Class and Object马晓星南京大学计算机软件研究所南京大学计算机科学与技术系1Institute of Computer SoftwareNanjing University关于对象式语言本课程并不系统讲授Eiffel语言但应学会“欣赏” Eiffel 语言 (比较“纯”)它首先是一个对象式程序设计语言但强调从分析到设计到实现的平滑过渡本课程主要讨论基于“类”的面向对象语言,但另有一些语言并不基于“类”概念。2Institute of Computer SoftwareOutlineThree worlds: Object-Oriented ModelingClass: the s
2、tatic structureObject: the run-time structureObject creation: from classes to objectsObject reference: linking up objects 3Institute of Computer SoftwareOutlineThree worlds: Object-Oriented ModelingClass: the static structureObject: the run-time structureObject creation: from classes to objectsObjec
3、t reference: linking up objects 4Institute of Computer SoftwareThree worlds客观世界 DVD播放机What is reality?复杂性 认识的主观性 问题世界抽象!Tell me not what you are but what you haveA model of a subset of the reality DVD播放机计算机(软件)世界A model of a model of a subset of the reality5Institute of Computer Software现实世界问题世界软件世界
4、RealityAbstract6Institute of Computer SoftwareOutlineThree worlds: Object-Oriented ModelingClass: the static structureObject: the run-time structureObject creation: from classes to objectsObject reference: linking up objects 7Institute of Computer SoftwareClass: the static structure类是对象式软件系统的基本组成单元类
5、的构成类的使用信息隐蔽设施模块与类型类如何构成系统?其它8Institute of Computer SoftwareClass“A class is an abstract data type equipped with a possibly partial implementation.” Deferred and effective class But why?9Institute of Computer SoftwareA very deferred classdeferred class COUNTER featureitem: INTEGER is deferred end- Co
6、unter valueup is- Increase item by 1.deferredensureitem = old item + 1enddown is- Decrease item by 1.deferredensureitem = old item 1endinvariantitem = 0end10ClassMold and instance类自身也能被当作对象么11Institute of Computer Software类的构成类名继承关系成员术语分类12Institute of Computer SoftwareAbstract data type POINTx: POI
7、NT REALy: POINT REAL: POINT REAL: POINT REALClass POINT: Choose a representation (polar, cartesian)In polar representation, and are attributes, x and y are routines.yx13A simple classclass POINT featurex, y: REAL- Point cartesian coordinatesmove (a, b: REAL) is- Move by a horizontally and by b verti
8、cally.dox := x + ay := y + bendscale (factor: REAL) is- Scale by factor.dox := factor * xy := factor * yend14Class 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
9、to horizontal axisdoendend15TerminologyA class is characterized by features. 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, no
10、rmally no effect). Every operation (routine or attribute call) is relative to a distinguished object, the current instance of the class. 16Alternative terminologyAttributes are also called instance variables or data member.Routines are also called methods, subprograms, or subroutines.Feature call ap
11、plying 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 attribute
12、or a routine as expressed by the Uniform Access principle17Feature categories by roleCommandQueryFeatureProcedureAttributeFunctionNo resultReturns resultComputationMemory18Feature categories by implementationProcedureAttributeFunctionRoutineReturns resultNo resultFeatureMemoryComputation19Feature ca
13、tegoriesCommandQueryFeatureProcedureAttributeFunctionNo resultReturns resultComputationMemoryRoutineReturns resultNo resultFeatureMemoryComputation20Uniform Accessbalance = list_of_deposits.total list_of_withdrawals.totallist_of_depositslist_of_withdrawalsbalancelist_of_depositslist_of_withdrawals(A
14、2)(A1)21The Principle of Uniform AccessFacilities managed by a module must be accessible to clients in the same way whether implemented by computation or storage.22Uniform access through feature callTo access a property of a point p1, the notation is the same regardless of the representation, e.g.p1
15、.xwhich is applicable both in cartesian representation (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 p
16、ossibly in terms of performance).23关于C+/Java的静态成员有力的设施但并非面向对象计算所必须?不修改静态数据成员的修改静态数据成员的破坏面向对象的“纯粹性” single target principle (see below )考虑类作为对象?24Institute of Computer Software类的使用类的使用有两种形式允引 (class A is a client of class B)继承 (class A is a descendant of class B) Client and supplier a:S in CFeature c
17、alla.some_feature or a.some_feature() or infix operatorsSingle target principle25Institute of Computer SoftwareUse of the class in a client (1/5)class GRAPHICS featurep, q: POINT- Graphic pointssome_routine is- Use p and q.local u, v: REALdo- Creation instructionscreate pcreate qendend0.00.0p(POINT)
18、0.00.0q(POINT)26Use 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:- Move (p, 4.0, -2.0)endend4.0-2.0p(POINT)0.00.0q(POINT)27Use of th
19、e 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)endend2.0-1.0p(POINT)0.00.0q(POINT)28Use of the class in a
20、 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 := qendend2.0-1.0p(POINT)0.00.0q(POINT)29
21、Use 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)en
22、dend2.0-1.0p(POINT)0.00.0q(POINT)30类的信息隐蔽设施回忆 C+和Java的信息隐蔽设施看Eiffel的设计细粒度的设计31Institute of Computer SoftwareApplying 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. An assignment su
23、ch as a1.attrib := a2 is syntactically illegal! (You cannot assign a value to an expression, e.g. x + y.)CAa1: A32The privileges of a clientSecretRead-onlyRead, restricted writeFull write33Applying abstraction principlesBeyond read access: full or restricted write, through exported procedures. Full
24、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_temperature (21.5).34Other uses of a setter procedureset_temperature (u: REAL) is- Set temperature value to u
25、.requirenot_under_minimum: u = -273not_above_maximum: u = 2000dotemperature := uupdate_databaseensuretemperature_set: temperature = uend35Delphi/C# “properties”Allowx.temperature := 21.5if there is a “setter”:private int temperature_internal;public int temperatureget return temperature_internal; set
26、 temperature_internal = value;/. Other instructions; .36Information hidingclass 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 a1.h: invalid anywhere (including in As own text). a1.j: valid only in B, C
27、 and their descendants(not valid in A!) a1.k: valid in B, C and their descendants, as well as in A and its descendants37Information hiding (contd)Information hiding only applies to use by clients, using dot notation or infix notation, as with a1.f (“Qualified calls”).Unqualified calls (within the cl
28、ass itself) are not subject to information hiding:class Afeature NONE h is - Does something.do . endfeature f is - Use h.do . hendend 38关于子类访问权限C+JavaEiffel and SmallTalk39Institute of Computer Software模块与类型的统一模块是软件分解的单元,是语法概念类型是某些动态对象的静态描述,是语义概念传统语言模块类型分离C语言的函数指针?对象语言 统一模块与类型40Institute of Computer
29、 SoftwareThe module-type mergeA class is both: A module A type From the module viewpoint: Set of available services (“features”). From the type viewpoint: Description of set of possible run-time objects (its instances).41Institute of Computer Software模块与类型的统一结合继承,威力更增Extension of the modularSpeciali
30、zation of the typeBut How?Every object is an instance of some class.Connection: The services of the class, viewed as a module, are the operations applicable to the instances of the class, viewed as a type.42Institute of Computer Software类如何构成系统?允引,允引,再允引第一驱动问题Root class and its creation procedure na
31、me“上帝之手”不应存在于对象软件正文之中。非集中式的架构避免直接指定动作顺序43Institute of Computer Software其它“纯”面向对象的效率问题基本类型对象式程序的风格 小方法编译优化效率不那么critical44Institute of Computer SoftwareOutlineThree worlds: Object-Oriented ModelingClass: the static structureObject: the run-time structureObject creation: from classes to objectsObject r
32、eference: linking up objects 45Institute of Computer Software例class A int x; ;void change1(A old, A cur) old = cur; void change2(A old, A cur)old.x=cur.x; a1, a2 均是A的实例,假设他们的x值不同change1(a1, a2);/ in Java? in C+?change2(a1, a2); / in Java? in C+? 46Institute of Computer Software对象系统的运行结构对象:A run-time
33、 instance of some class.某对象O是某类C的(直接)实例O包含为C中定义的属性(数据成员)当前状态(O的fields) 运行规律类定义的行为面向对象的软件系统运行时由一组对象构成。对象是对问题域对象,并进而对现实对象的实现,三种对象概念上的一致性与差异性 47Institute of Computer Software对象结构回头看Point类 和 point 对象简单类型的域与引用类型的域48Institute of Computer Software49Institute of Computer Software50Institute of Computer Soft
34、ware51Institute of Computer Software52Institute of Computer Software对象对象引用:A reference is a run-time value which is either void or attached. If attached, a reference identifies a single object (be attached to this object)对象的identity不同对象可有完全一样的域一个对象的域可随系统执行而变化53Institute of Computer Software对象引用声明cla
35、ss C feature . Endx:C看前面点的例子Self reference is possible54Institute of Computer Software运行时刻结构55Institute of Computer SoftwareOutlineThree worlds: Object-Oriented ModelingClass: the static structureObject: the run-time structureObject creation: from classes to objectsObject reference: linking up objec
36、ts 56Institute of Computer SoftwareObject creation对象按需创建,显式创建。传统技术往往基于栈分配实体运行时刻对象动态结构多变,而难以根据程序文本预测Eiffel 的对象创建基本创建基本创建 初始化featureCreation procedures57Institute of Computer SoftwareCreating an objectWith the class POINT as given:my_point: POINT .create my_pointEffect of such a creation instruction:A
37、llocate new object of the type declared for my_point.Initialize its fields to default values (0 for numbers, false for booleans, null for characters, void for references).Attach it to the instructions target, here my_point.58Specific creation proceduresclass POINT createmake_cartesian, make_polarfea
38、ture - Initializationmake_cartesian (a, b: REAL) is- Initialize to abscissa a, ordinate b.dox := ay := bendmake_polar .feature . The rest as before .59If there is a creation clauseCreation instructions must be “creation calls”, such ascreate my_point.make_polar (1, Pi/2)60If there is no creation cla
39、useAn absent creation clause, as inclass POINT - No creation clausefeature The rest as before endis 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 nothin
40、g; any class can redefine it to provide proper default initializations.61Associated conventionThe notationcreate xis understood (if permitted) as an abbreviation forcreate x.default_create62To allow both formsTo make both forms valid:create my_pointas well ascreate my_point.make_polar (1, Pi/2)it su
41、ffices to make default_create (redefined or not) one of the creation procedures:class POINT createmake_cartesian, make_polar, default_createfeature . The rest as before .63To prohibit instantiating a classclass NOT_CREATABLE create- Nothing here!feature . The rest as before .end64OutlineThree worlds
42、: Object-Oriented ModelingClass: the static structureObject: the run-time structureObject creation: from classes to objectsObject reference: linking up objects 65Institute of Computer SoftwareThe dynamic modelStates of a reference:Operations on references: create pp := qp := Voidif p = Void then .VO
43、IDATTACHEDcreate pp := q (where q is attached)p := Voidp := q (where q is void)pATTACHEDpVOID66Object reference回顾C+和Java的相应机制Void Reference, clone, copy and compare对象引用的问题引用类型与扩展类型 67Institute of Computer SoftwareForms of assignment and copyReference assignment (a and b of reference types): b := aOb
44、ject 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)68Shallow and deep cloningInitial situation:Result of:b := ac := clone (a)d := deep_clone (a)“Almaviva”namelandlordloved_oneaO1“Figaro”O2“Su
45、sanna”O3b“Almaviva”O4c“Almaviva”namelandlordloved_oneO5“Figaro”O6“Susanna”O7d69A related mechanism: Persistencea.store (file).b ?= retrieved (file)Storage is automatic. Persistent objects identified individually by keys. These features come from the library class STORABLE. The above is only an appro
46、ximate form (see typing discussion).70Object references对象引用的问题Dynamic Aliasing NO SURPRISE- Assume that here P (y) holdsx := yC (x) /not involve y textually- Then here P (y) still holds.71Institute of Computer Software引用类型与扩展类型72Institute of Computer SoftwareTypesReference types; value of an entity
47、is a reference. Example:b: POINTExpanded types; value of an entity is an object. Example:d: expanded POINTb(POINT)d(POINT)73Expanded classesA class may also be declared as expanded class C . The rest as usual .Then you can declare:a: Cwith the same effect asb: expanded Cin the earlier syntax (still permitted, with same meaning).74SubobjectsExpanded classes and entities support the notion of
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 智能用药机器人创业计划书
- 垃圾转运合同协议书模板
- 广告店合作合同协议书
- 民宿租赁合同协议书
- 企业安全生产合同协议书
- 旧房换新瓦合同协议书模板
- 农村一二三产业融合发展项目计划方案(八)
- 工艺品行业工艺品质量标准
- 供应链管理目标计划
- 梧州防火玻璃项目可行性研究报告
- 2025年高考数学二轮热点题型归纳与演练(上海专用)专题06数列(九大题型)(原卷版+解析)
- 2025中国铁路南宁局集团有限公司招聘高校毕业生32人四(本科及以上学历)笔试参考题库附带答案详解
- 国开政治经济学形考任务1-4试题及答案
- 第1章 整式的乘法(单元测试)(原卷)2024-2025学年湘教版七年级数学下册
- 《高中数学知识竞赛》课件
- 2025-2030年中国城市燃气行业发展分析及发展战略研究报告
- 人民医院关于印发对口支援工作管理办法(暂行)
- 施工现场环境保护措施试题及答案
- 2025年下半年浙江嘉兴市水务投资集团限公司招聘92人易考易错模拟试题(共500题)试卷后附参考答案
- 2025我国生产性服务业较快发展背后仍需关注三大问题
- 陕西省渭南市2025届高三教学质量检测(Ⅱ) 数学试题【含答案】
评论
0/150
提交评论