Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 Abstract Data Types and Encapsulation Concepts.

Similar presentations


Presentation on theme: "Chapter 11 Abstract Data Types and Encapsulation Concepts."— Presentation transcript:

1 Chapter 11 Abstract Data Types and Encapsulation Concepts

2 1-2 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

3 1-3 The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes. In a general sense, abstraction allows one to collect instances of entities into groups in which their common attributes need not be considered.

4 Example Suppose we define birds to be creatures with the following attributes: –two wings –two legs –a tail –feathers. Then, if we say a sparrow is a bird, a description of a sparrow need not include those attributes. The same is true for robins and woodpeckers. 1-4

5 Implications of the Previous Example These common attributes in the descriptions of specific species of birds can be abstracted away, because all species have them. Within a particular species, only the attributes that distinguish that species need be considered. 1-5

6 Implications of the Previous Example These common attributes in the descriptions of specific species of birds can be abstracted away, because all species have them. 1-6

7 Attributes Need Be Considered. Within a particular species, only the attributes that distinguish that species need be considered. 1-7

8 Example Sparrows have the attributes of being small and being noisy. A description of a sparrow needs to provide those attributes, but not the others that are common to all birds. 1-8

9 Advantages (1) This results in significant simplification of the descriptions of members of the species. 1-9

10 Advantages (2) In the world of programming languages, abstraction is a weapon against the complexity of programming; its purpose is to simplify the programming process. It is an effective weapon because it allows programmers to focus on essential attributes, while ignoring subordinate attributes. 1-10

11 Emergence of Data Abstraction The evolution of data abstraction began in 1960 with the first version of COBOL, which included the record data structure. The C-based languages have structs, which are also records. 1-11

12 Abstract Data Type Syntactically, an abstract data type is an enclosure that includes only –the data representation of one specific data type and –the subprograms that provide the operations for that type. 1-12

13 Hide Implementation Detail Through access controls, unnecessary details of the type can be hidden from units outside the enclosure that use the type. Program units that use an abstract data type can declare variables of that type, even though the actual representation is hidden from them. 1-13

14 Object An instance of an abstract data type is called an object. 1-14

15 Built-in Type The concept of an abstract data type, at least in terms of built-in types, is not a recent development. All built-in data types, even those of Fortran I, are abstract data types, although they are rarely called that. 1-15

16 Example For example, consider a floating-point data type. Most programming languages include at least one of these. A floating-point type –provides the means to create variables to store floating-point data and –also provides a set of arithmetic operations for manipulating objects of the type. 1-16

17 Key Concept in Data Abstraction Floating-point types in high-level languages employ a key concept in data abstraction: information hiding. 1-17

18 Information Hiding (1) The actual format of the floating-point data value in a memory cell is hidden from the user. The only operations available are those provided by the language. 1-18

19 Information Hiding (2) The user is not allowed to create new operations on data of the type, except those that can be constructed using the built-in operations. The user cannot directly manipulate the parts of the actual representation of values because that representation is hidden. 1-19

20 Information Hiding and Portability It is this feature that allows program portability between implementations of a particular language, even though the implementations may use different representations for particular data types. 1-20

21 User-defined Abstract Data Type A user-defined abstract data type should provide the same characteristics as those of language-defined types, such as a floating- point type: –(1) a type definition that allows program units to declare variables of the type but hides the representation of objects of the type; –(2) a set of operations for manipulating objects of the type. 1-21

22 Formal Definition of Abstract Data Type (1) An abstract data type is a data type that satisfies the following conditions: 1.The representation of objects of the type is hidden from the program units that use the type, so the only direct operations possible on those objects are those provided in the type’s definition. 1-22

23 Formal Definition of Abstract Data Type (2) 2. The declarations of the type and the protocols of the operations on objects of the type, which provide the type’s interface, are contained in a single syntactic unit. The type’s interface does not depend on  the representation of the objects or  the implementation of the operations. Also, other program units are allowed to create variables of the defined type. 1-23

24 Benefits of Information Hiding (1) Increased reliability. –Program units that use a specific abstract data type are called clients of that type. –Clients cannot manipulate the underlying representations of objects directly, either intentionally or by accident, thus increasing the integrity of such objects. –Objects can be changed only through the provided operations. 1-24

25 Benefits of Information Hiding (2) reduces the range of code and number of variables of which a programmer must be aware when writing or reading a part of the program. –The value of a particular variable can only be changed by code in a restricted range, making the code easier to understand and less challenging to find sources of incorrect changes. 1-25

26 Benefits of Information Hiding (3) makes name conflicts less likely, because the scope of variables is smaller. 1-26

27 Access Data Members Although the definition of abstract data types specifies that data members of objects must be hidden from clients, many situations arise in which clients need to access these data members. 1-27

28 Solution The common solution is to provide accessor methods, sometimes called getters and setters, that allow clients indirect access to the so- called hidden data —a better solution than simply making the data public, which would provide direct access. 1-28

29 Why Accessors Are Better (1) Read-only access can be provided, by having a getter method but no corresponding setter method. 1-29

30 Why Accessors Are Better (2) Constraints can be included in setters. –For example, if the data value should be restricted to a particular range, the setter can enforce that. 1-30

31 Why Accessors Are Better (3) The actual implementation of the data member can be changed without affecting the clients if getters and setters are the only access. 1-31

32 Caution Both specifying data in an abstract data type to be public and providing accessor methods for that data are violations of the principles of abstract data types. 1-32

33 Abstract Data Types in C++ 1-33

34 C++ and Abstract Data Type C++, which was first released in 1985, was created by adding features to C. The first important additions were those to support object-oriented programming. Because one of the primary components of object-oriented programming is abstract data types, C++ obviously is required to support them. 1-34

35 C++ Constructs That Support ADT C++ provides two constructs that are very similar to each other, the class and the struct, which directly support abstract data types. Because struct s are most commonly used when only data is included, we do not discuss them further here. 1-35

36 Access Public Entities of an Object C++ classes are types. A C++ program unit that declares an instance of a class can also access any of the public entities in that class, an instance of the class but only through. 1-36

37 Data Member and Member Function The data defined in a C++ class are called data members ; The functions ( methods ) defined in a class are called member functions. 1-37

38 Categories of DMs and MFs Data members and member functions appear in two categories: class and instance. Class members are associated with the class. Instance members are associated with the instances of the class. In this chapter, only the instance members of a class are discussed. 1-38

39 Share of MFs and DMs All of the instances of a class share a single set of member functions. But each instance has its own set of the class’s data members. 1-39

40 Types of Class Instances Class instances can be –static –stack dynamic or – heap dynamic. 1-40

41 Reference of Different Objects If static or stack dynamic, they are referenced directly with value variables. If heap dynamic, they are referenced through pointers. 1-41

42 Lifetime of a Stack Dynamic Instance Stack dynamic instances of classes are always created by the elaboration of an object declaration. Furthermore, the lifetime of such a class instance ends when the end of the scope of its declaration is reached. 1-42

43 Lifetime of Heap Dynamic Class Instances Heap dynamic class instances are created with the new operator and destroyed with the delete operator. 1-43

44 Pointer Data Members Both stack- and heap-dynamic classes can have pointer data members that reference heap dynamic data, so that even though a class instance is stack dynamic, it can include data members that reference heap dynamic data. 1-44

45 Approaches to Define a MF A member function of a class can be defined in two distinct ways: –the complete definition can appear in the class or –only in its header. 1-45

46 Implicitly Inlined MFs When both the header and the body of a member function appear in the class definition, the member function is implicitly inlined. Recall that this means that its code is placed in the caller’s code, rather than requiring the usual call and return linkage process. 1-46

47 Separately Defined MFs If only the header of a member function appears in the class definition, its complete definition appears outside the class and is separately compiled. 1-47

48 Rationale and Downside of Inlined MFs The rationale for allowing member functions to be inlined was to save function call overhead in real-time applications, in which run-time efficiency is of utmost importance. The downside of inlining member functions is that it clutters the class definition interface, resulting in a reduction in readability. 1-48

49 Hidden and Visible Entities A C++ class can contain both hidden and visible entities (meaning they are either hidden from or visible to clients of the class). Entities that are to be hidden are placed in a private clause, Visible, or public, entities appear in a public clause. 1-49

50 Constructor C++ allows the user to include constructor functions in class definitions, which are used to initialize the data members of newly created objects. A constructor may also allocate the heap- dynamic data that are referenced by the pointer members of the new object. 1-50

51 Properties of Constructors Constructors are implicitly called when an object of the class type is created. A constructor has the same name as the class whose objects it initializes. Constructors can be overloaded, but of course each constructor of a class must have a unique parameter profile. 1-51

52 Destructor A C++ class can also include a function called a destructor, which is implicitly called when the lifetime of an instance of the class ends. 1-52

53 Deallocate Pointer DMs As stated earlier, stack-dynamic class instances can contain pointer members that reference heap-dynamic data. The destructor function for such an instance can include a delete operator on the pointer members to deallocate the heap space they reference. 1-53

54 Purpose of a Destructor Destructors are often used as a debugging aid, in which case they simply display or print the values of some or all of the object’s data members before those members are deallocated. 1-54

55 Name of a Destructor The name of a destructor is the class’s name, preceded by a tilde ( ~ ). 1-55

56 Return Values of Constructors and Destructors Neither constructors nor destructors have return types, and neither use return statements. Both constructors and destructors can be explicitly called. 1-56

57 1-57 An Example in C++ class Stack { private: int *stackPtr, maxLen, topPtr; public: Stack() { // a constructor stackPtr = new int [100]; maxLen = 99; topPtr = -1; }; ~Stack () {delete [] stackPtr;}; void push (int number) { if (topSub == maxLen) cerr << ″Error in push - stack is full\n″; else stackPtr[++topSub] = number; }; void pop () {…}; int top () {…}; int empty () {…}; }

58 Description of the Class Definition (1) Objects of the Stack class are stack dynamic but include a pointer that references heap-dynamic data. The Stack class has three data members— stackPtr, maxLen, and topSub —all of which are private. –stackPtr is used to reference the heap- dynamic data, which is the array that implements the stack. Copyright © 2012 Addison-Wesley. All rights reserved. 1-58

59 Description of the Class Definition (2) The class also has four public member functions— push, pop, top, and empty —as well as a constructor and a destructor. All of the member function definitions are included in this class, although they could have been externally defined. Copyright © 2012 Addison-Wesley. All rights reserved. 1-59

60 Description of the Class Definition (3) Because the bodies of the member functions are included, they are all implicitly inlined. The constructor uses the new operator to allocate an array of 100 int elements from the heap. It also initializes maxLen and topSub. Copyright © 2012 Addison-Wesley. All rights reserved. 1-60

61 Example Program void main() { int topOne; Stack stk; //** Create an instance of the Stack class stk.push(42); stk.push(17); topOne = stk.top(); stk.pop();... } 1-61

62 A Stack class header file // Stack.h - the header file for the Stack class #include class Stack { private: //** These members are visible only to other //** members and friends (see Section 11.6.4) int *stackPtr; int maxLen; int topPtr; public: //** These members are visible to clients Stack(); //** A constructor ~Stack(); //** A destructor void push(int); void pop(); int top(); int empty(); } 1-62

63 The code file for Stack // Stack.cpp - the implementation file for the Stack class #include #include "Stack.h" using std::cout; Stack::Stack() { //** A constructor stackPtr = new int [100]; maxLen = 99; topPtr = -1; } Stack::~Stack() {delete [] stackPtr;}; //** A destructor void Stack::push(int number) { if (topPtr == maxLen) cerr << "Error in push--stack is full\n"; else stackPtr[++topPtr] = number; }... 1-63

64 Copyright © 2012 Addison-Wesley. All rights reserved. 1-64 Language Examples: Java Similar to C++, except: –All user-defined types are classes –All objects are allocated from the heap and accessed through reference variables –Individual entities in classes have access control modifiers (private or public), rather than clauses –Java has a second scoping mechanism, package scope, which can be used in place of friends All entities in all classes in a package that do not have access control modifiers are visible throughout the package

65 Copyright © 2012 Addison-Wesley. All rights reserved. 1-65 An Example in Java class StackClass { private: private int [] *stackRef; private int [] maxLen, topIndex; public StackClass() { // a constructor stackRef = new int [100]; maxLen = 99; topPtr = -1; }; public void push (int num) {…}; public void pop () {…}; public int top () {…}; public boolean empty () {…}; }

66 Copyright © 2012 Addison-Wesley. All rights reserved. 1-66 Parameterized Abstract Data Types Parameterized ADTs allow designing an ADT that can store any type elements – only an issue for static typed languages Also known as generic classes C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs

67 Copyright © 2012 Addison-Wesley. All rights reserved. 1-67 Parameterized ADTs in Ada Ada Generic Packages –Make the stack type more flexible by making the element type and the size of the stack generic generic Max_Size: Positive; type Elem_Type is private; package Generic_Stack is type Stack_Type is limited private; function Empty(Stk : in Stack_Type) return Boolean; function Top(Stk: in out StackType) return Elem_type;... private type List_Type is array (1..Max_Size) of Element_Type; type Stack_Type is record List : List_Type; Topsub : Integer range 0.. Max_Size := 0; end record; end Generic_Stack;

68 Parameterized ADTs in Ada (continued) Instantiations of the generic stack package Integer_Stack is new Generic_Stack(100,Integer); package Float_Stack is new Generic_Stack(100,Float); Copyright © 2012 Addison-Wesley. All rights reserved. 1-68

69 Copyright © 2012 Addison-Wesley. All rights reserved. 1-69 Parameterized ADTs in C++ Classes can be somewhat generic by writing parameterized constructor functions Stack (int size) { stk_ptr = new int [size]; max_len = size - 1; top = -1; }; A declaration of a stack object: Stack stk(150);

70 Copyright © 2012 Addison-Wesley. All rights reserved. 1-70 Parameterized ADTs in C++ (continued) The stack element type can be parameterized by making the class a templated class template class Stack { private: Type *stackPtr; const int maxLen; int topPtr; public: Stack() { // Constructor for 100 elements stackPtr = new Type[100]; maxLen = 99; topPtr = -1; } Stack(int size) { // Constructor for a given number stackPtr = new Type[size]; maxLen = size – 1; topSub = -1; }... } - Instantiation: Stack myIntStack;

71 Copyright © 2012 Addison-Wesley. All rights reserved. 1-71 Parameterized Classes in Java 5.0 Generic parameters must be classes Most common generic types are the collection types, such as LinkedList and ArrayList Eliminate the need to cast objects that are removed Eliminate the problem of having multiple types in a structure Users can define generic classes Generic collection classes cannot store primitives Indexing is not supported Example of the use of a predefined generic class: ArrayList myArray = new ArrayList (); myArray.add(0, 47); // Put an element with subscript 0 in it

72 Parameterized Classes in Java 5.0 (continued) import java.util.*; public class Stack2 { private ArrayList stackRef; private int maxLen; public Stack2)( { stackRef = new ArrayList (); maxLen = 99; } public void push(T newValue) { if (stackRef.size() == maxLen) System.out.println( " Error in push – stack is full " ); else stackRef.add(newValue);... } - Instantiation: Stack2 myStack = new Stack2 (); Copyright © 2012 Addison-Wesley. All rights reserved. 1-72

73 Copyright © 2012 Addison-Wesley. All rights reserved. 1-73 Parameterized Classes in C# 2005 Similar to those of Java 5.0, except no wildcard classes Predefined for Array, List, Stack, Queue, and Dictionary Elements of parameterized structures can be accessed through indexing

74 Copyright © 2012 Addison-Wesley. All rights reserved. 1-74 Encapsulation Constructs Large programs have two special needs: –Some means of organization, other than simply division into subprograms –Some means of partial compilation (compilation units that are smaller than the whole program) Obvious solution: a grouping of subprograms that are logically related into a unit that can be separately compiled (compilation units) Such collections are called encapsulation

75 Copyright © 2012 Addison-Wesley. All rights reserved. 1-75 Nested Subprograms Organizing programs by nesting subprogram definitions inside the logically larger subprograms that use them Nested subprograms are supported in Ada, Fortran 95+, Python, JavaScript, and Ruby

76 Copyright © 2012 Addison-Wesley. All rights reserved. 1-76 Encapsulation in C Files containing one or more subprograms can be independently compiled The interface is placed in a header file Problem: the linker does not check types between a header and associated implementation #include preprocessor specification – used to include header files in applications

77 Copyright © 2012 Addison-Wesley. All rights reserved. 1-77 Encapsulation in C++ Can define header and code files, similar to those of C Or, classes can be used for encapsulation –The class is used as the interface (prototypes) –The member definitions are defined in a separate file Friends provide a way to grant access to private members of a class

78 Copyright © 2012 Addison-Wesley. All rights reserved. 1-78 Ada Packages Ada specification packages can include any number of data and subprogram declarations Ada packages can be compiled separately A package’s specification and body parts can be compiled separately

79 Copyright © 2012 Addison-Wesley. All rights reserved. 1-79 C# Assemblies A collection of files that appears to application programs to be a single dynamic link library or executable Each file contains a module that can be separately compiled A DLL is a collection of classes and methods that are individually linked to an executing program C# has an access modifier called internal ; an internal member of a class is visible to all classes in the assembly in which it appears

80 Copyright © 2012 Addison-Wesley. All rights reserved. 1-80 Naming Encapsulations Large programs define many global names; need a way to divide into logical groupings A naming encapsulation is used to create a new scope for names C++ Namespaces –Can place each library in its own namespace and qualify names used outside with the namespace –C# also includes namespaces

81 Copyright © 2012 Addison-Wesley. All rights reserved. 1-81 Naming Encapsulations (continued) Java Packages –Packages can contain more than one class definition; classes in a package are partial friends –Clients of a package can use fully qualified name or use the import declaration Ada Packages –Packages are defined in hierarchies which correspond to file hierarchies –Visibility from a program unit is gained with the with clause

82 Copyright © 2012 Addison-Wesley. All rights reserved. 1-82 Naming Encapsulations (continued) Ruby classes are name encapsulations, but Ruby also has modules Typically encapsulate collections of constants and methods Modules cannot be instantiated or subclassed, and they cannot define variables Methods defined in a module must include the module’s name Access to the contents of a module is requested with the require method -

83 Copyright © 2012 Addison-Wesley. All rights reserved. 1-83 Summary The concept of ADTs and their use in program design was a milestone in the development of languages Two primary features of ADTs are the packaging of data with their associated operations and information hiding Ada provides packages that simulate ADTs C++ data abstraction is provided by classes Java’s data abstraction is similar to C++ Ada, C++, Java 5.0, and C# 2005 support parameterized ADTs C++, C#, Java, Ada, and Ruby provide naming encapsulations


Download ppt "Chapter 11 Abstract Data Types and Encapsulation Concepts."

Similar presentations


Ads by Google