资源预览内容
第1页 / 共63页
第2页 / 共63页
第3页 / 共63页
第4页 / 共63页
第5页 / 共63页
第6页 / 共63页
第7页 / 共63页
第8页 / 共63页
第9页 / 共63页
第10页 / 共63页
亲,该文档总共63页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
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 abstraction, 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 extracting 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 constructs 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 abstract 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 that 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 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()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 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 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 Encapsulation11 / 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 nameconstructor 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 initialized 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. 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 classNo 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 = 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: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: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 2024OutlinelRecap 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 lPerforms 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 allowedSoftware Design II Data Abstraction and Encapsulation24 / 6231 July 2024Destructors 析构函数在对象生命周期结束时,回收其所占用的内存空间。析构函数是“反向”的构造函数,析构函数不允许有返回值,不带参数,一个类中只有一个。析构函数的作用正好与构造函数相反。当对象超出其作用范围,对应的内存空间被系统回收或被程序用delete删除时,析构函数将被调用。Software Design II Data Abstraction and Encapsulation25 / 6231 July 2024When Constructors 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 called 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 program 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 Calledcreate.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)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 (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 Object 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 member 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 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 capabilities 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 the 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 of 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 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 Encapsulation43 / 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 capability 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 modification: 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 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 Hiding: 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 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 - 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 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 of 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 always 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 II 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 objectUse 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 Memberwise 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 (call-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 OutputSoftware 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 Encapsulation60 / 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 Rumbaugh 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 / 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!
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号