《软件设计课件:Lecture 05 Data Abstraction and Encapsulation》由会员分享,可在线阅读,更多相关《软件设计课件:Lecture 05 Data Abstraction and Encapsulation(63页珍藏版)》请在金锄头文库上搜索。
1、Lecture 05 Data Abstraction & EncapsulationSoftware Design II Data Abstraction and Encapsulation2 / 6231 July 2024Design and programming are human activities;forget that and all is lost.-Bjarne Stroustrup, 1991Software Design II Data Abstraction and Encapsulation3 / 6231 July 2024OutlinelRecap abstr
2、action, object & classlInitializing class objects: constructorslDestructorslData members and member FunctionslInformation hiding & encapsulationlUML and software reusabilitySoftware Design II Data Abstraction and Encapsulation4 / 6231 July 2024Defining AbstractionlAbstraction is the process of extra
3、cting common features from specific examples lAbstraction is a process of defining the essential concepts while ignoring the inessential detailsSoftware Design II Data Abstraction and Encapsulation5 / 6231 July 2024Different Types of AbstractionlData AbstractionProgramming languages define construct
4、s to simplify the way information is presented to the programmer lFunctional AbstractionProgramming languages have constructs that gift wrap very complex and low level instructions into instructions that are much more readablelObject AbstractionOOP languages take the concept even further and abstrac
5、t programming constructs as objects. Software Design II Data Abstraction and Encapsulation6 / 6231 July 2024Anything that you can describe in your OOP program can be represented as an object, and that representation can be created, manipulated and destroyed to represent how you use the real object t
6、hat it models. Everything is an ObjectSoftware Design II Data Abstraction and Encapsulation7 / 6231 July 2024An object is a self-contained entity with attributes and behaviorsDefining an Objectinformation an object must know:identity uniqueness attributes structurestate current conditionbehavior an
7、object must do:methods what it can doevents what it responds toSoftware Design II Data Abstraction and Encapsulation8 / 6231 July 2024Class as AbstractionlA class is an abstraction of its instances. It defines all the attributes and methods that its instances must also have.PersonnamesexagetellSex()
8、tellAge()Software Design II Data Abstraction and Encapsulation9 / 6231 July 2024lA Class acts as the template from which an instance of an object is created. The class defines the properties of the object and the methods used to control the objects behavior. lA Class specifies the structure of data
9、as well as the methods which manipulate that data. Such data and methods are contained in each instance of the class.lA Class is a model or template that can be instantiated to create objects with a common definition, and therefore common properties, operations and behavior. Defining a ClassSoftware
10、 Design II Data Abstraction and Encapsulation10 / 6231 July 2024OutlinelRecap abstraction, object & classlInitializing class objects: constructorslDestructorslData members and member FunctionslInformation hiding & encapsulationlUML and software reusabilitySoftware Design II Data Abstraction and Enca
11、psulation11 / 6231 July 202411Constructors are methods which set the initial state of an objectConstructors are called when an object is createdA default constructor is a constructor with no parameters and do nothingRestrictions on constructorsconstructor name must be the same as the class nameconst
12、ructor cannot return a value, not even voidonly initialize attributes of the objectConstructorsSoftware Design II Data Abstraction and Encapsulation12 / 6231 July 2024ConstructorslConstructor function Can initialize class membersSame name as the class, no return typeMember variables can be initializ
13、ed by the constructor or set afterwardslDefining objectsInitializers can be providedInitializers passed as arguments to the class constructorSoftware Design II Data Abstraction and Encapsulation13 / 6231 July 2024lFormat ClassName objectName( value1, value2, );Constructor assigns value1, value2, etc
14、. to its member variablesIf not enough values specified, rightmost parameters set to their default (specified by programmer)MyClass myObject( 3, 4.0 );ConstructorsSoftware Design II Data Abstraction and Encapsulation14 / 6231 July 2024Default Arguments with ConstructorslDefault constructorOne per cl
15、assNo arguments or all default argumentsCan be invoked without argumentslDefault arguments (缺省参数需要在函数声明的时候写上,如果定义跟声明分开,则在定义函数的时候不需要在写上缺省参数)Set in default constructor function prototype (in class definition)Do not set defaults in the function definition, outside of a class Example:SampleClass( int =
16、0, float = 0);Constructor has same name as classSoftware Design II Data Abstraction and Encapsulation15 / 6231 July 2024Using Constructorstime2.htime2.cpp (Part 1 of 2)time2.cpp (Part 2 of 2)fig16_07.cpp (Part 1 of 2)fig16_07.cpp (Part 2 of 2)Constructed with:Constructed with:all arguments defaulted
17、:all arguments defaulted: 00:00 00:00 12:00:00 AM 12:00:00 AMhour specified; minute and second defaulted:hour specified; minute and second defaulted: 02:00 02:00 2:00:00 AM 2:00:00 AMhour and minute specified; second defaulted:hour and minute specified; second defaulted: 21:34 21:34 9:34:00 PM 9:34:
18、00 PMhour, minute, and second specified:hour, minute, and second specified: 12:25 12:25 12:25:42 PM 12:25:42 PMall invalid values specified:all invalid values specified: 00:00 00:00 12:00:00 AM 12:00:00 AMProgram OutputSoftware Design II Data Abstraction and Encapsulation22 / 6231 July 2024OutlinelR
19、ecap abstraction, object & classlInitializing class objects: constructorslDestructorslData members and member FunctionslInformation hiding & encapsulationlUML and software reusabilitySoftware Design II Data Abstraction and Encapsulation23 / 6231 July 2024Destructors lMember function of class lPerfor
20、ms termination housekeeping before the system reclaims the objects memory lComplement of the constructor lName is tilde () followed by the class nameTimeRecall that the constructors name is the class namelReceives no parameters, returns no value (无形参定义)lOne destructor per class - no overloading allo
21、wedSoftware Design II Data Abstraction and Encapsulation24 / 6231 July 2024Destructors 析构函数在对象生命周期结束时,回收其所占用的内存空间。析构函数是“反向”的构造函数,析构函数不允许有返回值,不带参数,一个类中只有一个。析构函数的作用正好与构造函数相反。当对象超出其作用范围,对应的内存空间被系统回收或被程序用delete删除时,析构函数将被调用。Software Design II Data Abstraction and Encapsulation25 / 6231 July 2024When Cons
22、tructors and Destructors Are CalledlConstructors and destructors called automaticallyOrder depends on scope of objectslGlobal scope objects (在main函数外声明的变量)Constructors called before any other function (including main)Destructors called when main terminates (or exit function called) Destructors not c
23、alled if program terminates with abortSoftware Design II Data Abstraction and Encapsulation26 / 6231 July 2024lAutomatic local objects Constructors called when objects definedDestructors called when objects leave scope (when the block in which they are defined is exited)Destructors not called if pro
24、gram ends with exit or abortlstatic local objectsConstructors called when execution reaches the point where the objects are definedDestructors called when main terminates or the exit function is calledDestructors not called if the program ends with abortWhen Constructors and Destructors Are Calledcr
25、eate.hcreate.cppfig16_08.cpp (Part 1 of 2)fig16_08.cpp (Part 2 of 2)Object 1 constructor (global created before main)Object 1 constructor (global created before main)Object 2 constructor (local automatic in main)Object 2 constructor (local automatic in main)Object 3 constructor (local static in main
26、)Object 3 constructor (local static in main)Object 5 constructor (local automatic in create)Object 5 constructor (local automatic in create)Object 6 constructor (local static in create)Object 6 constructor (local static in create)Object 7 constructor (local automatic in create)Object 7 constructor (
27、local automatic in create)Object 7 destructor Object 7 destructor Object 5 destructor Object 5 destructor Object 4 constructor (local automatic in main)Object 4 constructor (local automatic in main)Object 4 destructor Object 4 destructor Object 2 destructor Object 2 destructor Object 6 destructor Ob
28、ject 6 destructor Object 3 destructor Object 3 destructor Object 1 destructor Object 1 destructor Program OutputSoftware Design II Data Abstraction and Encapsulation32 / 6231 July 2024OutlinelRecap abstraction, object & classlInitializing class objects: constructorslDestructorslData members and memb
29、er FunctionslInformation hiding & encapsulationlUML and software reusabilitySoftware Design II Data Abstraction and Encapsulation33 / 6231 July 2024Data Members and Member FunctionslClasses provide public member functions Set (i.e., write) or get (i.e., read) values of private data membersE.g., one
30、action to operate the private data members of class lNamingMember function that sets interestRate typically named setInterestRateMember function that gets interestRate would typically be called getInterestRateSoftware Design II Data Abstraction and Encapsulation34 / 6231 July 2024lDo set and get cap
31、abilities effectively make data members public?No! Programmer decides what the function can set and what information the function can getlpublic set functions shouldCheck attempts to modify data membersEnsure that the new value is appropriate for that data itemExample: an attempt to set the day of t
32、he month to 37 would be rejectedProgrammer must include these featuresData Members and Member Functionstime3.h (Part 1 of 2)time3.h (Part 2 of 2)time3.cpp (Part 1 of 3)time3.cpp (Part 2 of 3)time3.cpp (Part 3 of 3)fig16_09.cpp (Part 1 of 3)fig16_09.cpp (Part 2 of 3)fig16_09.cpp (Part 3 of 3)Result o
33、f setting all valid values:Result of setting all valid values: Hour: 17 Minute: 34 Second: 25 Hour: 17 Minute: 34 Second: 25 Result of attempting to set invalid hour and second:Result of attempting to set invalid hour and second: Hour: 0 Minute: 43 Second: 0 Hour: 0 Minute: 43 Second: 0 Incrementing
34、 minute 3 times:Incrementing minute 3 times:Start time: 11:58:00 AMStart time: 11:58:00 AMminute + 1: 11:59:00 AMminute + 1: 11:59:00 AMminute + 1: 12:00:00 PMminute + 1: 12:00:00 PMminute + 1: 12:01:00 PM minute + 1: 12:01:00 PM Program OutputProgram OutputSoftware Design II Data Abstraction and En
35、capsulation43 / 6231 July 2024A Subtle Trap: Returning a Reference to a Private Data Member lReference to an object Alias for the name of the object Can be used on the left side of an assignment statementReference can receive a value, which changes the original object as welllOne way to use this cap
36、ability Have a public member function of a class return a non-const reference to a private data memberThis reference can be modified, which changes the original datatime4.htime4.cpp (Part 1 of 2)time4.cpp (Part 2 of 2)fig16_10.cpp (Part 1 of 2)fig16_10.cpp (Part 2 of 2)Program OutputHour before modi
37、fication: 20Hour before modification: 20Hour after modification: 30Hour after modification: 30 *POOR PROGRAMMING PRACTICE!POOR PROGRAMMING PRACTICE!badSetHour as an lvalue, Hour: 74badSetHour as an lvalue, Hour: 74*Software Design II Data Abstraction and Encapsulation49 / 6231 July 2024OutlinelRecap
38、 abstraction, object & classlInitializing class objects: constructorslDestructorslData members and member FunctionslInformation hiding & encapsulationlUML and software reusabilitySoftware Design II Data Abstraction and Encapsulation50 / 6231 July 2024Information Hiding & EncapsulationlInformation Hi
39、ding: Each program component should hide as much information as possible from the users of the component.lEncapsulation is the process of hiding an objects implementation from another object, while presenting only the interfaces that should be visible.An object should be self-governingAny changes to
40、 the objects state (its variables) should be accomplished by that objects methodsEncapsulation lets you protect information in your objects from being used incorrectlySoftware Design II Data Abstraction and Encapsulation51 / 6231 July 2024EncapsulationlYou can take two views of an object:internal -
41、the structure of its data, the algorithms used by its methodsexternal - the interaction of the object with other objects in the programlFrom the external view, an object is an encapsulated entity, providing serviceslThese services define the interface to the objectSoftware Design II Data Abstraction
42、 and Encapsulation52 / 6231 July 2024EncapsulationlAn encapsulated object can be thought of as a black box lIts inner workings are hidden to the client, which only invokes the interface methodsClientClientMethodsDataSoftware Design II Data Abstraction and Encapsulation53 / 6231 July 2024Principles o
43、f Encapsulation “Dont ask how I do it, but this is what I can do”- The encapsulated object“I dont care how, just do your job, and Ill do mine”- One encapsulated object to anotherSoftware Design II Data Abstraction and Encapsulation54 / 6231 July 2024Encapsulating a ClasslMembers of a class must alwa
44、ys be declared with the minimum level of visibility.lProvide setters and getters (also known as accessors/mutators) to allow controlled access to private data.lProvide other public methods (known as interfaces ) that other objects must adhere to in order to interact with the object.Software Design I
45、I Data Abstraction and Encapsulation55 / 6231 July 2024Setters and Getterspublic:void setSex(char s) / validate heresex = s;char getSex() / format herereturn sex;private: char sex;lSetters and Getters allow controlled access to class datalSetters are methods that (only) alter the state of an objectU
46、se setters to validate data before changing the object statelGetters are methods that (only) return information about the state of an objectUse getters to format data before returning the objects stateSoftware Design II Data Abstraction and Encapsulation56 / 6231 July 2024Assignment by Default Membe
47、rwise Copy lAssignment operator (= =)Sets variables equal, i.e., x = = y; ;Can be used to assign an object to another object of the same typeMemberwise copy member by member copymyObject1 = = myObject2; ;lObjects may be (will be introduced later)Passed as function argumentsReturned from functions (c
48、all-by-value default)Use pointers for call by referencefig16_11.cpp (Part 1 of 2)fig16_11.cpp (Part 2 of 2)date1 = 7-4-1993date1 = 7-4-1993date2 = 1-1-1990date2 = 1-1-1990 After default memberwise copy, date2 = 7-4-1993After default memberwise copy, date2 = 7-4-1993Program OutputProgram OutputSoftwa
49、re Design II Data Abstraction and Encapsulation59 / 6231 July 2024OutlinelRecap abstraction, object & classlInitializing class objects: constructorslDestructorslData members and member FunctionslInformation hiding & encapsulationlUML and software reusabilitySoftware Design II Data Abstraction and En
50、capsulation60 / 6231 July 2024Unified Model LanguagelUML is a general-purpose modeling language of software engineeringlIt provides a set of graphic notation techniques to create visual models of object-oriented software-intensive systems. lIt was developed by Grady Booch, Ivar Jacobson and James Ru
51、mbaugh at Rational Software in the 1990slIt was adopted by the Object Management Group (OMG) in 1997lIn 2000 the UML was accepted by the International Organization for Standardization (ISO) as a standard for modeling software-intensive systems.Software Design II Data Abstraction and Encapsulation61
52、/ 6231 July 2024Class DiagramsSoftware Design II Data Abstraction and Encapsulation62 / 6231 July 2024Software Reusability lObject-oriented programmers Concentrate on implementing useful classeslTremendous opportunity to capture and catalog classes Accessed by large segments of the programming community Class libraries exist for this purposelSoftware Constructed from existing, well-defined, carefully tested, portable, widely available componentsSpeeds development of powerful, high-quality softwareSoftware Design II Data Abstraction and Encapsulation63 / 6231 July 2024Thank you!