類和對象范本學習培訓模板課件_第1頁
類和對象范本學習培訓模板課件_第2頁
類和對象范本學習培訓模板課件_第3頁
類和對象范本學習培訓模板課件_第4頁
類和對象范本學習培訓模板課件_第5頁
已閱讀5頁,還剩89頁未讀 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

1、類和對象Class and Object關于對象式語言2022/8/6Institute of Computer Software, Nanjing University2本課程并不系統(tǒng)講授Eiffel語言但應學會“欣賞” Eiffel 語言 (比較“純”)它首先是一個對象式程序設計語言但強調(diào)從分析到設計到實現(xiàn)的平滑過渡摘要2022/8/6Institute of Computer SoftwareNanjing University3三個世界: 面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結構對象:運行時刻的結構對象創(chuàng)建:從類到對象對象引用:對象串起來摘要三個世界: 面向?qū)ο蟮慕C嫦驅(qū)ο笤?/p>

2、則類:對象程序靜態(tài)的結構對象:運行時刻的結構對象創(chuàng)建:從類到對象對象引用:對象串起來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現(xiàn)實世界問題世界軟件世界Reality抽象摘要2022/8/6Institute of Computer SoftwareNanjing University7三個世界: 面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結構對象:運行時刻的結構對象創(chuàng)建:從類到對象對象引用:對象串起來面向?qū)ο笤瓌t2022/8/6Institute of Computer Software, Nanjing University8Object OrientationEncapsul

4、ationAbstractionPolymorphismInheritance面向?qū)ο笤瓌t2022/8/6Institute of Computer Software, Nanjing University9Object OrientationEncapsulationAbstractionPolymorphismInheritance回顧:抽象數(shù)據(jù)類型2022/8/6Institute of Computer Software, Nanjing University10抽象數(shù)據(jù)類型(ADT):用數(shù)學方法定義對象集合和運算集合,僅通過運算的性質(zhì)刻畫數(shù)據(jù)對象,而獨立于計算機中可能的表示方法ADT

5、規(guī)約方法代數(shù)規(guī)范語法部分,公理部分ADT實現(xiàn)E1,E2,E3面向?qū)ο笤瓌t2022/8/6Institute of Computer Software, Nanjing University11Object OrientationEncapsulationAbstractionPolymorphismInheritance封裝2022/8/6Institute of Computer Software, Nanjing University12封裝是把過程和數(shù)據(jù)包圍起來,對數(shù)據(jù)的訪問只能通過已定義的界面。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封裝信息/實現(xiàn)隱藏InterfaceClientDeposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number Deposit() Withdraw() Transfer() 2022/8/6Institute of Computer SoftwareNanjing University15封裝封裝使得對象在抽象所界定的范圍內(nèi)保持相對的獨立,從而保證對象設計和對象實施方法的可靠分離。設計者和使用者分離!封裝可以防止由于程序模塊之間的

8、互相依賴性而導致程序“不穩(wěn)定”不會因某個部分的修改而導致整個系統(tǒng)許多部分都發(fā)生改動。封裝是相對的!不能也沒有必要阻止編程人員去查看實施細節(jié)。2022/8/6Institute of Computer SoftwareNanjing University16封裝 vs. 繼承矛盾嗎?No!封裝性主要指的是對象的封裝性,引入繼承機制后,對象仍然是封裝地很好的實體,其它對象與它通信只能發(fā)送消息。相似性:共享代碼!繼承:靜態(tài)共享代碼封裝:動態(tài)共享代碼2022/8/6Institute of Computer SoftwareNanjing University17模塊化傳統(tǒng)的模塊劃分方法:要求組成的子

9、程序(模塊)有實際意義和明確的某個功能功能分解和結構分解OO的模塊劃分目標:生成一組有助于降低系統(tǒng)開發(fā)費用的模塊,通過模塊劃分所得到的模塊應該能夠保證可以獨立的生成和修改,每個模塊的結構應該足夠簡單2022/8/6Institute of Computer SoftwareNanjing University18模塊化與抽象和封裝密切相關模塊的劃分是以抽象出來的對象的性質(zhì)和功能為依據(jù)的模塊是封裝得以實現(xiàn)的技術保障Booch:“模塊化是反映一個被分解成一組相關聯(lián)的松散結合模塊組成系統(tǒng)的一個特性?!蹦K化以模塊為基礎2022/8/6Institute of Computer SoftwareNan

10、jing University19模塊與類型的統(tǒng)一模塊是軟件分解的單元,是語法概念類型是某些動態(tài)對象的靜態(tài)描述,是語義概念傳統(tǒng)語言 模塊與類型分離對象語言 模塊與類型統(tǒng)一類型:類是抽象數(shù)據(jù)類型的實現(xiàn)模塊:類是對象式程序的基本組成單元基于類的面向?qū)ο蟮恼Z言機制的強有力之處在于“類”統(tǒng)一了類型和模塊面向?qū)ο笤瓌t2022/8/6Institute of Computer Software, Nanjing University20Object OrientationEncapsulationAbstractionPolymorphismInheritance2022/8/6Institute of

11、Computer SoftwareNanjing University21層次性封裝性幫助隱藏細節(jié);模塊化使結構更加有序,但仍然不夠!層次性是對抽象的排序和定位類結構關系(“is a”)對象結構關系(“part of”)實現(xiàn)方式繼承:子類,父類單繼承,多繼承聚合:擁有關系/組合關系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繼承繼承 作為模塊擴展機制,體現(xiàn)開閉原則,較好地支持軟件的復用。繼承 作為類型特化機制,體現(xiàn)分類方法,更合理地支持子類型實現(xiàn)。繼承也是多態(tài)和動態(tài)綁定機制的基礎。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面向?qū)ο笤瓌t2022/8/6Institute of Computer Software, Nanjing University32Object OrientationE

17、ncapsulationAbstractionPolymorphismInheritance2022/8/6Institute of Computer SoftwareNanjing University33多態(tài)多態(tài)性使指相同的操作或函數(shù)、過程可作用于多種類型的對象上并獲得不同的結果。不同的對象,收到同一消息可以產(chǎn)生不同的結果,這種現(xiàn)象稱為多態(tài)性。多態(tài)性允許每個對象以適合自身的方式去響應共同的消息多態(tài)性增強了軟件的靈活性和重用性。2022/8/6Institute of Computer SoftwareNanjing University34多態(tài)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; / 向數(shù)組里添加類型 for(int i = 0; i s.leng

19、th; i+) si = randShape(); / 用多態(tài)的方法調(diào)用 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. 類的實例在運行時刻產(chǎn)生,他們是對象。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 訪問一致性原則客戶應能以實現(xiàn)無關的方式訪問模塊的功能,不管這個功能是通過存儲還是計算來實現(xiàn)的。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模塊與類型的統(tǒng)一從模塊的觀點: 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三個世界: 面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結構對象:運行時刻的結構對象創(chuàng)建:從類到對象對象引用:對象串起來對象:系統(tǒng)的運行結構對象:A run-time instance of some class.某對

48、象O是某類C的(直接)實例O包含為C中定義的屬性(數(shù)據(jù)成員)當前狀態(tài)(O的fields) 運行規(guī)律類定義的行為面向?qū)ο蟮能浖到y(tǒng)運行時由一組對象構成。對象是對問題域?qū)ο?,并進而對現(xiàn)實對象的實現(xiàn),三種對象概念上的一致性與差異性 2022/8/6Institute of Computer Software, Nanjing University69DVD播放機對象有狀態(tài)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三個世界: 面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結構對象:運行時刻的結構對象創(chuàng)建:從類到對象對象引用:對象串起來對象創(chuàng)建對象按需創(chuàng)建,顯式創(chuàng)建。傳統(tǒng)技術往往基于棧分配實體運行時刻對象動態(tài)結構多變,而難以根據(jù)程序文本預測Eiffel 的對象創(chuàng)建基本創(chuàng)建基本創(chuàng)建 初始化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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論