Download presentation
Presentation is loading. Please wait.
Published byMiljan Simonović Modified over 6 years ago
1
Abstract Data Types and Encapsulation Concepts
Chapter 11 Abstract Data Types and Encapsulation Concepts
2
Chapter 11 Topics Steve Adds: Motivation and History of Abstraction
The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations Copyright © 2015 Pearson. All rights reserved.
3
Motivation of Abstracti
As Software has Become more Complex, it Requires more Software Engineers F. Brooks - Mythical Man Month s Work done in 2 months by 1 Software Engineer > Work done in 1 month by 2 SEs! “Adding Software Engineers to a Late Project will only Make it Later!” WHY? Interconnectedness: Interdependencies in Code Individual Portions can’t be Written in Isolation Information Exchange Needed Between SEs Complexity Historically Controlled by Abstracting Away Less Important Details
4
Separation of Concerns
Divide and Conquer Problem Solving Technique Identify the Different Aspects of Problem Time Considerations - Scheduling Focus on Qualities of Primary Concern Alternate Views of Problem - Data vs. Control Size-Oriented Decomposition Today’s Applications involve Interoperability of New C/S, Legacy, COTS, Databases, etc. Multiple Prog. Languages (C, C++, Java, etc.) Heterogeneous Hardware/OS Platforms Separation of Concerns is Critical!
5
History of Abstraction Procedures and Modules
The “First” Abstraction Mechanism Repeated Execution of Same Code without Duplication Inefficient at Information Hiding Modules: Managing Name Spaces Public: Portion Accessible Outside Module Private: Portion Accessible Inside Module Users can Only “See” Information Needed to Utilize Module SE can Only “See” Information Needed to Code Module Supports Information Hiding
6
Modularity Compose and Design Systems as Set of Modules
Two-Phase Application of Separation of Concerns Define Details of Individual Modules Characterize Interactions Among All Modules Three Goals of Modularity Decomposability: Problem to Subproblems Composability: Combine to Solution Abstraction: Capability of Understanding Levels of Modules in Programming C: “.h/.c” Pairs - Ad-hoc Modularity C++: “.h/.c” Pairs for Classes Ada95/Java: Adds the Package Concept Maximize Cohesion and Minimize Coupling
7
Abstraction Remove/Hide Unimportant Details to Allow more Important Aspects of a Product to be Considered Widely Utilized to Reduce Complexity Abstractions Dominate Computing Paradigms (OO, Top-Down, Functional, etc.) Design Models (CRC, OMT, UML, etc.) Programming Languages (C, C++, Java, etc.) People Think and Learn in Abstractions Goals of Advances in Design and Programming Provide Robust Sets of Abstractions Allow Modeling to Occur Close to Real World
8
The Concept of Abstraction
An abstraction is a view or representation of an entity that includes only the most significant attributes The concept of abstraction is fundamental in programming (and computer science) Nearly all programming languages support process abstraction with subprograms Nearly all programming languages designed since 1980 support data abstraction Copyright © 2015 Pearson. All rights reserved.
9
Introduction to Data Abstraction
An abstract data type is a user-defined data type that satisfies the following two conditions: The representation of objects of the type is hidden from the program units that use these objects, so the only operations possible are those provided in the type's definition The declarations of the type and the protocols of the operations on objects of the type are contained in a single syntactic unit. Other program units are allowed to create variables of the defined type. Copyright © 2015 Pearson. All rights reserved.
10
Advantages of Data Abstraction
Advantages the first condition Reliability--by hiding the data representations, user code cannot directly access objects of the type or depend on the representation, allowing the representation to be changed without affecting user code Reduces the range of code and variables of which the programmer must be aware Name conflicts are less likely Advantages of the second condition Provides a method of program organization Aids modifiability (everything associated with a data structure is together) Separate compilation Copyright © 2015 Pearson. All rights reserved.
11
Abstract Data Types (ADTs)
Proposed by B. Liskov (MIT) for CLU in 1975 ADTs Promote Application Development From Perspective of Information and its Usage ADT Design Process: Identify “Kinds” or “Types” of Information Encapsulate Information and Provide a Public Interface of Methods Hide Information and Method Code in the Private Implementation ADTs Correspond to User-Defined Data Types Analogous to Integer Data Type and +, -, *, etc.
12
Abstract Data Types (ADTs)
Consider the following Example Stack ADT: Public Interface User PUSH POP TOP EMPTY Private Implementation Designer Head: Int; ST: Array[100] of Int; Push(X Int) … End; Int Pop() TOP 5 10 15 20 PUSH 20 15 10 5 ST
13
ADT Design Guidelines Separation of Concerns and Modularity
Problem Decomposable into Components Abstraction and Representation Independence Hiding Implementation of Components Changing without Impacting External View Incrementality and Anticipation of Change Components are Changed, Added, Refined, etc., as Needed to Support Evolving Requirements Cohesion: Well-Defined Component Performs a Single Task or has a Single Objective Coupling: Component Interactions are Known and Minimal
14
Benefits of ADT Paradigm
Supports Reusable Software Components Creation and Testing in Isolation Integration of Working Components Designers/Developers View Problem at Higher Level of Abstraction Controls Information Consistency Public Interface Limits Access to Data Private Implementation Unavailable Promotes/Facilitates Software Evolution/Reuse Inheritance to Extend Design/Class Library Multiple Instances of Same Class
15
High-Tech Supermarket System (HTSS)
Automate the Functions and Actions Cashiers and Inventory Updates User Friendly Grocery Item Locator Fast-Track Deli Orderer Inventory Control User System Interfaces Cash Register/UPC Scanner GUI for Inventory Control Shopper Interfaces Locator and Orderer Deli Interface for Deli Workers We’ll Introduce and Utilize Throughout Course
16
The HTSS Software Architecture
SDO EDO IL Item SDO EDO IL ItemDB Local Server IL Payment CR CR IC Order CR Non-Local Client Int. IC CR IL: Item Locator CreditCardDB CR: Cash Register Inventory Control IC: Invent. Control ATM-BanKDB DO: Deli Orderer for Shopper/Employee ItemDB Global Server OrderDB SupplierDB
17
Programming with ADTs ADTs Promote Applications Development From Perspective of Information and Its Usage ADT Design Process and Steps: Identify Major “Kinds/Types” of Information Describe Purpose Each Kind or Type Encapsulate Information Define and Characterize Methods Process Iterates/Cycles from Bottom Up Focus on Lowest Level of Info. - Build ADTs Next Level of ADTs Use Lowest Level Next Level Combines most Recent Levels Repeat to Achieve Desired System level
18
ADTs in HTSS ADT Item; PRIVATE DATA: SET OF Item(s), Each Item Contains: UPC, Name, WCost, RCost, OnShelf, InStock, Location, ROLimit; PTR TO Current_Item; PUBLIC OPS: Create_New_Item(UPC, ...) : RETURN Status; Get_Item_NameCost(UPC) : RETURNS (STRING, REAL); Modify_Inventory(UPC, Delta) ; Get_InStock_Amt(UPC) : RETURN INTEGER; Get_OnShelf_Amt(UPC) : RETURN INTEGER; Check_If_On_Shelf(UPC): RETURN BOOLEAN; Time_To_Reorder(UPC): RETURN BOOLEAN; Get_Item_Profit(UPC): RETURN REAL; ... {notes: - OPS span the entire application - not limited to a single, functional component} END Item; ADT DeliItem; ADT CustomerInfo; PRIVATE DATA: SET OF (Item, Weight, CostLb, Increm); END CustomerInfo; END DeliItem;
19
ADTs in HTSS ADT Process_Order; {middle-level ADT}
PRIVATE DATA: {local variables to process an order} PUBLIC OPS : {what do you think are appropriate?} {this ADT uses the ADT/PUBLIC OPS from Item, Deli_Item, Receipt, Coupons, and Customer_Info to process and total an Order.} END Process_Order; ADT Sales_Info; {middle-level ADT} PRIVATE DATA: {local variables to collate sales information} {this ADT uses the ADT/PUBLIC OPS from Receipt so that the sales information for the store can be maintained.} END Sales_Info; ADT Cashier; {high-level ADT} {this ADT uses the ADT/PUBLIC OPS from the middle-level ADTs (Process_Order, Sales_Info, etc.).) END Cashier;
20
Advantages/Drawbacks of ADTs
Abstraction is Promoted and Achieved Concurrent Engineering is Feasible Reuse and Evolution are Attainable Emphasizes Static System Behavior Drawbacks: Without Inheritance, Redundancies Likely Dynamic System Behavior Still Difficult Associations Between ADTs Difficult Only Inclusion Association Supported Do Drawbacks Outweigh Advantages?
21
Language Requirements for ADTs
A syntactic unit in which to encapsulate the type definition A method of making type names and subprogram headers visible to clients, while hiding actual definitions Some primitive operations must be built into the language processor Copyright © 2015 Pearson. All rights reserved.
22
Design Issues Can abstract types be parameterized?
What access controls are provided? Is the specification of the type physically separate from its implementation? Copyright © 2015 Pearson. All rights reserved.
23
Language Examples: C++
Based on C struct type and Simula 67 classes The class is the encapsulation device A class is a type All of the class instances of a class share a single copy of the member functions Each instance of a class has its own copy of the class data members Instances can be static, stack dynamic, or heap dynamic Copyright © 2015 Pearson. All rights reserved.
24
Language Examples: C++ (continued)
Information Hiding Private clause for hidden entities Public clause for interface entities Protected clause for inheritance (Chapter 12) Copyright © 2015 Pearson. All rights reserved.
25
Language Examples: C++ (continued)
Constructors: Functions to initialize the data members of instances (they do not create the objects) May also allocate storage if part of the object is heap-dynamic Can include parameters to provide parameterization of the objects Implicitly called when an instance is created Can be explicitly called Name is the same as the class name Copyright © 2015 Pearson. All rights reserved.
26
Language Examples: C++ (continued)
Destructors Functions to cleanup after an instance is destroyed; usually just to reclaim heap storage Implicitly called when the object’s lifetime ends Can be explicitly called Name is the class name, preceded by a tilde (~) Copyright © 2015 Pearson. All rights reserved.
27
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 () {…}; } Copyright © 2015 Pearson. All rights reserved.
28
A Stack class header file
// Stack.h - the header file for the Stack class #include <iostream.h> class Stack { private: //** These members are visible only to other //** members and friends (see Section ) 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(); } Copyright © 2015 Pearson. All rights reserved.
29
The code file for Stack // Stack.cpp - the implementation file for the Stack class #include <iostream.h> #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; ... Copyright © 2015 Pearson. All rights reserved.
30
Language Examples: C++ (continued)
Friend functions or classes - to provide access to private members to some unrelated units or functions Necessary in C++ Copyright © 2015 Pearson. All rights reserved.
31
Language Examples – Objective-C
Interface containers @interface class-name: parent-class { instance variable declarations } method prototypes @end Implementation containers @implementation class-name method definitions Classes are types Copyright © 2015 Pearson. All rights reserved.
32
Language Examples – Objective-C (continued)
Method prototypes form (+ | -) (return-type) method-name [: (formal-parameters)]; - Plus indicates a class method - Minus indicates an instance method - The colon and the parentheses are not included when there are no parameters - Parameter list format is different - If there is one parameter (name is meth1:) -(void) meth1: (int) x; - For two parameters -(int) meth2: (int) x second: (float) y; - The name of the method is meth2:: Copyright © 2015 Pearson. All rights reserved.
33
Language Examples – Objective-C (continued)
Method call syntax [object-name method-name]; Examples: [myAdder add1: 7]; [myAdder add1: 7: 5: 3]; - For the method: -(int) meth2: (int) x second: (float) y; the call would be like the following: [myObject meth2: 7 second: 3.2]; Copyright © 2015 Pearson. All rights reserved.
34
Language Examples – Objective-C (continued)
Constructors are called initializers – all they do is initialize variables Initializers can have any name – they are always called explicitly Initializers always return self Objects are created by calling alloc and the constructor Adder *myAdder = [[Adder alloc] init]; All class instances are heap dynamic Copyright © 2015 Pearson. All rights reserved.
35
Language Examples – Objective-C (continued)
To import standard prototypes (e.g., i/o) #import <Foundation/Foundation.h> The first thing a program must do is allocate and initialize a pool of storage for its data (pool’s variable is pool in this case) NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; At the end of the program, the pool is released with: [pool drain]; Copyright © 2015 Pearson. All rights reserved.
36
Language Examples – Objective-C (continued)
Information Hiding The are used to specify the access of instance variables. The default access is protected (private in C++) There is no way to restrict access to methods The name of a getter method is always the name of the instance variable The name of a setter method is always the word set with the capitalized variable’s name attached If the getter and setter for a variable does not impose any constraints, they can be implicitly generated (called properties) Copyright © 2015 Pearson. All rights reserved.
37
Language Examples – Objective-C (continued)
// stack.m – interface and implementation for a simple stack #import Stack: NSObject { int stackArray[100], stackPtr,maxLen, topSub; } -(void) push: (int) number; -(void) pop; -(int) top; Stack -(Stack *) initWith { maxLen = 100; topSub = -1; stackPtr = stackArray; return self; Copyright © 2015 Pearson. All rights reserved.
38
Language Examples – Objective-C (continued)
// stack.m – continued -(void) push: (int) number { if (topSub == maxLen) in push – stack is full″); else stackPtr[++topSub] = number; ... } Copyright © 2015 Pearson. All rights reserved.
39
Language Examples – Objective-C (continued)
An example use of stack.m Placed in of stack.m int main (int argc, char *argv[]) { int temp; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; Stack *myStack = [[Stack alloc] initWith]; [myStack push: 5]; [myStack push: 3]; temp = [myStack top]; element is: %i″, temp); [myStack pop]; myStack pop]; [myStack release]; [pool drain]; return 0; } Copyright © 2015 Pearson. All rights reserved.
40
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 - Implicit garbage collection of all objects 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 Copyright © 2015 Pearson. All rights reserved.
41
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 () {…}; } Copyright © 2015 Pearson. All rights reserved.
42
Language Examples: C# Based on C++ and Java
Adds two access modifiers, internal and protected internal All class instances are heap dynamic Default constructors are available for all classes Garbage collection is used for most heap objects, so destructors are rarely used structs are lightweight classes that do not support inheritance Copyright © 2015 Pearson. All rights reserved.
43
Language Examples: C# (continued)
Common solution to need for access to data members: accessor methods (getter and setter) C# provides properties as a way of implementing getters and setters without requiring explicit method calls Copyright © 2015 Pearson. All rights reserved.
44
C# Property Example public class Weather {
public int DegreeDays { //** DegreeDays is a property get {return degreeDays;} set { if (value < 0 || value > 30) Console.WriteLine( "Value is out of range: {0}", value); else degreeDays = value;} } private int degreeDays; ... Weather w = new Weather(); int degreeDaysToday, oldDegreeDays; w.DegreeDays = degreeDaysToday; oldDegreeDays = w.DegreeDays; Copyright © 2015 Pearson. All rights reserved.
45
Abstract Data Types in Ruby
Encapsulation construct is the class Local variables have “normal” names Instance variable names begin with “at” signs Class variable names begin with two “at” signs Instance methods have the syntax of Ruby functions (def … end) Constructors are named initialize (only one per class)—implicitly called when new is called If more constructors are needed, they must have different names and they must explicitly call new Class members can be marked private or public, with public being the default Classes are dynamic Copyright © 2015 Pearson. All rights reserved.
46
Abstract Data Types in Ruby (continued)
class StackClass { def initialize @stackRef = Array.new @maxLen = 100 @topIndex = -1 end def push(number) puts " Error in push – stack is full" else @topIndex + 1 = number def pop … end def top … end def empty … end Copyright © 2015 Pearson. All rights reserved.
47
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++, Java 5.0, and C# 2005 provide support for parameterized ADTs Copyright © 2015 Pearson. All rights reserved.
48
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); Copyright © 2015 Pearson. All rights reserved.
49
Parameterized ADTs in C++ (continued)
The stack element type can be parameterized by making the class a templated class template <class Type> 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<int> myIntStack; Copyright © 2015 Pearson. All rights reserved.
50
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 <Integer> myArray = new ArrayList <Integer> (); myArray.add(0, 47); // Put an element with subscript 0 in it Copyright © 2015 Pearson. All rights reserved.
51
Parameterized Classes in Java 5.0 (continued)
import java.util.*; public class Stack2<T> { private ArrayList<T> stackRef; private int maxLen; public Stack2)( { stackRef = new ArrayList<T> (); 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<string> myStack = new Stack2<string> (); Copyright © 2015 Pearson. All rights reserved.
52
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 Copyright © 2015 Pearson. All rights reserved.
53
Generics (Parameterized ADT)
Classic Programming Problem Develop Stack or List Code in C that Applies to a Single Type (e.g., List of DeliItems) Need Same Code for ProduceItems, MeatItems, etc., Copy and Edit Original Code Minimal Reuse, Error Prone, Time Consuming What do Generics Offer? A Type-Parameterizable Class Abstracts Similar Behavior into a Common Interface Reusable and Consistent Class Illustrate via C++
54
A Generic Stack Class template <class T> stack { private: T* st,
int top; int size; public: void stack(int x) {st = new T[x]; top = 0; size = x;} stack() {st = new T[100]; top = 0; size = 100;} ~stack() {delete st;} push(T entry) { st[top++] = entry;} }; main() { stack<int> S1(10); // Creates int Stack with 10 Slots stack<char> S2; // Creates char Stack with 100 Slots stack<Item> ItemDB(10000); // Stack of Grocery Items }
55
A Generic Set Class template <class ItemType> class Set {
DLList<ItemType>* _members; // Set Templates Uses Double-Linked List Template public: Set() { _members = new DLList<ItemType>(); } void Add(ItemType* member) {_members->queue(member);} void Remove(ItemType* member) {_members->remove(member);} int Member(ItemType* member) {return _members->isMember(member);} int NullSet(){return _members->isEmpty();} } main() { Set<int> IntSet; // Creates an Integer Set Set<Item> ItemDB; // Creates an Item Set }
56
Benefits of Generics Strong Promotion of Reuse Develop Once, Use Often
stack and Set Examples Eliminate Errors and Inconsistencies Between Similar and Separate Classes Simplifies Maintenance Problems Focuses on Abstraction and Design Promotes Correctness and Consistent Program Behavior Once Designed/Developed, Reused with Consistent Results If Problems, Corrections in Single Location
57
Abstract Classes And Methods
Cannot be Instantiated Can only be Subclassed Keyword “abstract” before Keyword “class” is used to Define an Abstract Class Example of an Abstract Class is Number in the java.lang Package Abstract Methods Abstract Classes may contain Abstract Methods This allows an Abstract Class to Provide all its Subclasses with the Method Declarations for all the Methods
58
A Sample Abstract Class
abstract class Item { protected String UPC, Name; protected int Quantity; protected double RetailCost, WholeCost; public Item() { ... }; abstract public void finalize(); abstract public boolean Modify_Inventory(int Delta); public int Get_InStock_Amt() {...}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(double NewPrice);{...}; };
59
Another Abstract Class and Methods
abstract class GraphicsObject{ int x, y; void moveTo(int x1,y1) { } abstract void draw(); } class Circle extends GraphicsObject{ void draw() { } class Rectangle extends GraphicsObject{
60
Interfaces in Java Design-Level Multiple Inheritance Java Interface
Set of Methods (no Implementations) Set (Possibly Empty) of Constant Values Interfaces Utilized Extensively Throughout Java APIs to Acquire and Pass on Functionality Threads in Java - Multiple Concurrent Tasks Subclassing from Thread Class (java.lang API) Implementing an Interface of Runnable Class
61
A Sample Interface in Java
Teaching Student Employee / \ | UnderGrad Graduate Faculty interface Teaching { int NUMSTUDENTS = 25; void recordgrade(Undergrad u, int score); void advise(Undergrad u); ... etc ... } class Graduate extends Student implements Teaching{ ...} class Faculty extends Employee implements Teaching{ recordgrade() Different for Graduate & Faculty
62
Quasi Generics in Java class Set implements Coll{
void add(Object obj){ ... } void delete(Object obj){ } interface Coll { int MAXIMUM = 500; void add(Object obj); void delete(Object obj); Object find(Object obj); int currentCount(); } class Queue implements Coll{ void add(Object obj){ ... } void delete(Object obj){ }
63
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 Copyright © 2015 Pearson. All rights reserved.
64
Nested Subprograms Organizing programs by nesting subprogram definitions inside the logically larger subprograms that use them Nested subprograms are supported in Python, JavaScript, and Ruby Copyright © 2015 Pearson. All rights reserved.
65
Encapsulation in C Files containing one or more subprograms can be independently compiled The interface is placed in a header file Problem 1: the linker does not check types between a header and associated implementation Problem 2: the inherent problems with pointers #include preprocessor specification – used to include header files in applications Copyright © 2015 Pearson. All rights reserved.
66
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 Copyright © 2015 Pearson. All rights reserved.
67
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 Copyright © 2015 Pearson. All rights reserved.
68
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 Copyright © 2015 Pearson. All rights reserved.
69
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 Copyright © 2015 Pearson. All rights reserved.
70
Naming Encapsulations (continued)
Ruby Modules: - 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 Copyright © 2015 Pearson. All rights reserved.
71
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++ C++, Java 5.0, and C# 2005 support parameterized ADTs C++, C#, Java, and Ruby provide naming encapsulations Copyright © 2015 Pearson. All rights reserved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.