类和对象范本学习培训模板课件_第1页
类和对象范本学习培训模板课件_第2页
类和对象范本学习培训模板课件_第3页
类和对象范本学习培训模板课件_第4页
类和对象范本学习培训模板课件_第5页
已阅读5页,还剩89页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、类和对象Class and Object关于对象式语言2022/8/6Institute of Computer Software, Nanjing University2本课程并不系统讲授Eiffel语言但应学会“欣赏” Eiffel 语言 (比较“纯”)它首先是一个对象式程序设计语言但强调从分析到设计到实现的平滑过渡摘要2022/8/6Institute of Computer SoftwareNanjing University3三个世界: 面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来摘要三个世界: 面向对象的建模面向对象原

2、则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来2022/8/6Institute of Computer Software, Nanjing University4三个世界2022/8/6Institute of Computer Software, Nanjing University5客观世界 DVD播放机What is reality?复杂性 认识的主观性 问题世界抽象!A model of a subset of the reality DVD播放机计算机(软件)世界A model of a model of a subset of the rea

3、lity2022/8/662022/8/6Institute of Computer SoftwareNanjing University现实世界问题世界软件世界Reality抽象摘要2022/8/6Institute of Computer SoftwareNanjing University7三个世界: 面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来面向对象原则2022/8/6Institute of Computer Software, Nanjing University8Object OrientationEncapsul

4、ationAbstractionPolymorphismInheritance面向对象原则2022/8/6Institute of Computer Software, Nanjing University9Object OrientationEncapsulationAbstractionPolymorphismInheritance回顾:抽象数据类型2022/8/6Institute of Computer Software, Nanjing University10抽象数据类型(ADT):用数学方法定义对象集合和运算集合,仅通过运算的性质刻画数据对象,而独立于计算机中可能的表示方法ADT

5、规约方法代数规范语法部分,公理部分ADT实现E1,E2,E3面向对象原则2022/8/6Institute of Computer Software, Nanjing University11Object OrientationEncapsulationAbstractionPolymorphismInheritance封装2022/8/6Institute of Computer Software, Nanjing University12封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。DVD播放机2022/8/6Institute of Computer SoftwareNa

6、njing University13封装Professor 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)2022/8/6Inst

7、itute of Computer SoftwareNanjing University14封装信息/实现隐藏InterfaceClientDeposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number Deposit() Withdraw() Transfer() 2022/8/6Institute of Computer SoftwareNanjing University15封装封装使得对象在抽象所界定的范围内保持相对的独立,从而保证对象设计和对象实施方法的可靠分离。设计者和使用者分离!封装可以防止由于程序模块之间的

8、互相依赖性而导致程序“不稳定”不会因某个部分的修改而导致整个系统许多部分都发生改动。封装是相对的!不能也没有必要阻止编程人员去查看实施细节。2022/8/6Institute of Computer SoftwareNanjing University16封装 vs. 继承矛盾吗?No!封装性主要指的是对象的封装性,引入继承机制后,对象仍然是封装地很好的实体,其它对象与它通信只能发送消息。相似性:共享代码!继承:静态共享代码封装:动态共享代码2022/8/6Institute of Computer SoftwareNanjing University17模块化传统的模块划分方法:要求组成的子

9、程序(模块)有实际意义和明确的某个功能功能分解和结构分解OO的模块划分目标:生成一组有助于降低系统开发费用的模块,通过模块划分所得到的模块应该能够保证可以独立的生成和修改,每个模块的结构应该足够简单2022/8/6Institute of Computer SoftwareNanjing University18模块化与抽象和封装密切相关模块的划分是以抽象出来的对象的性质和功能为依据的模块是封装得以实现的技术保障Booch:“模块化是反映一个被分解成一组相关联的松散结合模块组成系统的一个特性。”模块化以模块为基础2022/8/6Institute of Computer SoftwareNan

10、jing University19模块与类型的统一模块是软件分解的单元,是语法概念类型是某些动态对象的静态描述,是语义概念传统语言 模块与类型分离对象语言 模块与类型统一类型:类是抽象数据类型的实现模块:类是对象式程序的基本组成单元基于类的面向对象的语言机制的强有力之处在于“类”统一了类型和模块面向对象原则2022/8/6Institute of Computer Software, Nanjing University20Object OrientationEncapsulationAbstractionPolymorphismInheritance2022/8/6Institute of

11、Computer SoftwareNanjing University21层次性封装性帮助隐藏细节;模块化使结构更加有序,但仍然不够!层次性是对抽象的排序和定位类结构关系(“is a”)对象结构关系(“part of”)实现方式继承:子类,父类单继承,多继承聚合:拥有关系/组合关系2022/8/6Institute of Computer SoftwareNanjing University22继承单继承CheckingSavingsSuperclass (parent)SubclassesInheritance RelationshipAncestorDescendents2022/8/6I

12、nstitute of Computer SoftwareNanjing University23继承多继承Use multiple inheritance only when needed and always with caution!Multiple Inheritance2022/8/6Institute of Computer SoftwareNanjing University24继承继承 作为模块扩展机制,体现开闭原则,较好地支持软件的复用。继承 作为类型特化机制,体现分类方法,更合理地支持子类型实现。继承也是多态和动态绑定机制的基础。2022/8/6Institute of C

13、omputer SoftwareNanjing University25子类对父类的扩展与特化继承表达的是一种分类演绎的认识方法“To program is to understand.” 特化:包含范围变小,行为特殊化扩展:增加新的操作重定义:改变行为2022/8/6Institute of Computer SoftwareNanjing University26The Open-Closed Principle (OCP)动机:软件是变化的!开闭原则:“Closed for Modification; Open for Extension”对修改关闭,对扩展开放!Why OCP? - 重

14、用How OCP? - 继承The 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

15、 it now. For keeping modules open (developers perspective): One frequently overlooks aspects of the problem.2022/8/6Institute of Computer Software, Nanjing University27The Open-Closed Principle (1)Institute of Computer SoftwareNanjing UniversityACEDB2022/8/6The Open-Closed Principle (2)Institute of

16、Computer SoftwareNanjing UniversityACEDBFAGH I2022/8/6The Open-Closed Principle (3)Institute of Computer SoftwareNanjing UniversityACEDBFAGH I2022/8/62022/8/6Institute of Computer SoftwareNanjing University31Example面向对象原则2022/8/6Institute of Computer Software, Nanjing University32Object OrientationE

17、ncapsulationAbstractionPolymorphismInheritance2022/8/6Institute of Computer SoftwareNanjing University33多态多态性使指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。多态性允许每个对象以适合自身的方式去响应共同的消息多态性增强了软件的灵活性和重用性。2022/8/6Institute of Computer SoftwareNanjing University34多态ShapeCircleTriangleSqua

18、redraw()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 Square(); case 2: return new Triangle(); public static void main(String args) Shape s = new Shape3; / 向数组里添加类型 for(int i = 0; i s.leng

19、th; i+) si = randShape(); / 用多态的方法调用 for(int i = 0; i = 0end2022/8/6Institute of Computer Software, Nanjing University40类的构成类名继承关系成员术语分类2022/8/6Institute of Computer Software, Nanjing University41Abstract data type POINTx: POINT REALy: POINT REAL: POINT REAL: POINT REALClass POINT: Choose a represen

20、tation (polar, cartesian)In polar representation, and are attributes, x and y are routines.2022/8/6Institute of Computer Software, Nanjing University42yxA simple classclass POINT featurex, y: REAL- Point cartesian coordinatesmove (a, b: REAL) is- Move by a horizontally and by b vertically.dox := x +

21、 ay := y + bendscale (factor: REAL) is- Scale by factor.dox := factor * xy := factor * yend2022/8/6Institute of Computer Software, Nanjing University43Class 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

22、:= sqrt (x2 + y2)endtheta: REAL is- Angle to horizontal axisdoendend2022/8/6Institute of Computer Software, Nanjing University44术语A class is an implementation of an abstract data type. Instances of the class may be created at run-time; they are objects. 类的实例在运行时刻产生,他们是对象。Every object is an instance

23、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.2022/8/6Institute of Computer Software, Nanjing University45术语A class is characterized by features.

24、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

25、 a distinguished object, the current instance of the class. 2022/8/6Institute of Computer Software, Nanjing University46Feature categories by role2022/8/6Institute of Computer Software, Nanjing University47CommandQueryFeatureProcedureAttributeFunctionNo resultReturns resultComputationMemoryFeature c

26、ategories by implementation2022/8/6Institute of Computer Software, Nanjing University48ProcedureAttributeFunctionRoutineReturns resultNo resultMemoryComputationFeatureFeature categories2022/8/6Institute of Computer Software, Nanjing University49CommandQueryFeatureProcedureAttributeFunctionNo resultR

27、eturns resultComputationMemoryRoutineReturns resultNo resultMemoryComputationFeatureAlternative terminologyAttributes are also called instance variables or data member.Routines are also called methods, subprograms, or subroutines.Feature call applying a certain feature of a class to an instance of t

28、hat 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 or a routine as expressed by the Uniform Access princip

29、le.2022/8/6Institute of Computer Software, Nanjing University50回顾:Uniform Access 访问一致性原则客户应能以实现无关的方式访问模块的功能,不管这个功能是通过存储还是计算来实现的。Facilities managed by a module must be accessible to clients in the same way whether implemented by computation or storage.2022/8/6Institute of Computer Software, Nanjing U

30、niversity51Uniform Accessbalance = list_of_deposits.total list_of_withdrawals.total2022/8/6Institute of Computer SoftwareNanjing University52list_of_depositslist_of_withdrawalsbalancelist_of_depositslist_of_withdrawals(A2)(A1)Uniform access through feature callTo access a property of a point p1, the

31、 notation is the same regardless of the representation, e.g.p1.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

32、 to be performed. There is no difference for clients (except possibly in terms of performance).2022/8/6Institute of Computer Software, Nanjing University53类的使用类的使用有两种形式允引 (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

33、 a.some_feature() or infix operatorsSingle target principle2022/8/6Institute of Computer Software, Nanjing University54Use 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 qendend2022/8

34、/6Institute of Computer Software, Nanjing University550.00.0p(POINT)0.00.0q(POINT)Use 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:-

35、 Move (p, 4.0, -2.0)endend2022/8/6Institute of Computer Software, Nanjing University564.0-2.0p(POINT)0.00.0q(POINT)Use 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.

36、0)- Compare with Pascal, C, Ada:- Move (p, 4.0, -2.0)p.scale (0.5)endend2022/8/6Institute of Computer Software, Nanjing University572.0-1.0p(POINT)0.00.0q(POINT)Use 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- Creatio

37、n 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 := qendend2022/8/6Institute of Computer Software, Nanjing University582.0-1.0p(POINT)0.00.0q(POINT)Use of the class in a client (5/5)class GRAPHICS featurep, q

38、: 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)endend2022/8/6Institute of Computer Software, Nanjing Universi

39、ty592.0-1.0p(POINT)0.00.0q(POINT)2022/8/6Institute of Computer SoftwareNanjing University60模块与类型的统一从模块的观点: 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

40、of the class, viewed as a module, are the operations applicable to the instances of the class, viewed as a type.Applying 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. 2022/8/6Inst

41、itute of Computer Software, Nanjing University61CAa1: AThe privileges of a client2022/8/6Institute of Computer Software, Nanjing University62SecretRead-onlyRead, restricted writeFull writeApplying abstraction principlesBeyond read access: full or restricted write, through exported procedures. Full w

42、rite 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).2022/8/6Institute of Computer Software, Nanjing University63Other uses of a setter procedur

43、eset_temperature (u: REAL) is- Set temperature value to u.requirenot_under_minimum: u = -273not_above_maximum: u = 2000dotemperature := uupdate_databaseensuretemperature_set: temperature = uend2022/8/6Institute of Computer Software, Nanjing University64Delphi/C# “properties”Allowx.temperature := 21.

44、5if there is a “setter”:private int temperature_internal;public int temperatureget return temperature_internal; set temperature_internal = value;/. Other instructions; .2022/8/6Institute of Computer Software, Nanjing University65Information hiding2022/8/6Institute of Computer Software, Nanjing Unive

45、rsity66class 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 and their descendants(not valid in A!) a1.k: valid in B, C and the

46、ir descendants, as well as in A and its descendantsInformation 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 class itself) are not subject to information hiding:class Afeature NONE

47、 h is - Does something.do . endfeature f is - Use h.do . hendend 2022/8/6Institute of Computer Software, Nanjing University67DVD播放机摘要2022/8/6Institute of Computer SoftwareNanjing University68三个世界: 面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来对象:系统的运行结构对象:A run-time instance of some class.某对

48、象O是某类C的(直接)实例O包含为C中定义的属性(数据成员)当前状态(O的fields) 运行规律类定义的行为面向对象的软件系统运行时由一组对象构成。对象是对问题域对象,并进而对现实对象的实现,三种对象概念上的一致性与差异性 2022/8/6Institute of Computer Software, Nanjing University69DVD播放机对象有状态The state of an object is one of the possible conditions in which an object may exist.The state of an object normall

49、y changes over time.2022/8/6Institute of Computer Software, Nanjing University70Name: J ClarkEmployee ID: 567138Date Hired: July 25, 1991Status: TenuredDiscipline: FinanceMaximum Course Load: 3 classesProfessor Clark对象有行为Behavior determines how an object acts and reacts.The visible behavior of an ob

50、ject is modeled by the set of messages it can respond to (operations the object can perform).2022/8/6Institute of Computer Software, Nanjing University71SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()SetMaxLoad()Name: J ClarkEmployee ID: 567138HireDate: 07/25/1991Status: TenuredDiscipline:

51、 FinanceMaxLoad: 3Professor Clark对象有标识Each object has a unique identity, even if the state is identical to that of another object.2022/8/6Institute of Computer Software, Nanjing University72Professor “J Clark” teaches BiologyProfessor “J Clark” teaches Biology对象需要合作Objects are useless unless they ca

52、n 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 through messages.2022/8/6Institute of Computer Software, Nanjing University73对象 vs. 类

53、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.2022/8/6Institute of Computer Software, Nanjing University74ObjectsProfes

54、sor SmithProfessor MellonFrom Real WorldabstractingClass: ProfessorTo computer WorldinstancingObjects摘要2022/8/6Institute of Computer SoftwareNanjing University75三个世界: 面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来对象创建对象按需创建,显式创建。传统技术往往基于栈分配实体运行时刻对象动态结构多变,而难以根据程序文本预测Eiffel 的对象创建基本创建基本创建 初始化fe

55、atureCreation procedures2022/8/6Institute of Computer Software, Nanjing University76Creating 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 default values (0 f

56、or numbers, false for booleans, null for characters, void for references).Attach it to the instructions target, here my_point.2022/8/6Institute of Computer Software, Nanjing University77Specific creation proceduresclass POINT createmake_cartesian, make_polarfeature - Initializationmake_cartesian (a,

57、 b: REAL) is- Initialize to abscissa a, ordinate b.dox := ay := bendmake_polar .feature . The rest as before .2022/8/6Institute of Computer Software, Nanjing University78If there is a creation clauseCreation instructions must be “creation calls”, such ascreate my_point.make_polar (1, Pi/2)2022/8/6In

58、stitute of Computer Software, Nanjing University79If there is no creation clauseAn 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 nothing; any class can redefine it to provide proper default initializations.2022/8/6Institute of Computer Software, Nanjing University80Associated conventionThe notationcreate xis understood (if permitted) as an abbrevi

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论