Reference: R.Sebesta, Chapters 11, 12 COS220 Concepts of PLs AUBG, COS dept Lecture 21 OOP Data Encapsulation Reference: R.Sebesta, Chapters 11, 12 R.Lafore, Chapter 6 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Lecture Contents: Introducing the concept of a class as an abstract data type /ADT/ and as collection of data members (components) and member functions (methods). Classes as user defined data types. The relation class – object. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev The OOP concept From Structured Programming Algorithms + Data Structures = Programs Thinking in Functions! To Object Oriented Programming Classes + Objects = Programs Thinking in Classes! 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev The OOP concept Structured Programming: the core concept is dividing a program into functions and modules – separate program units At least 2 problems with Structured Programming: The Mythical Man-Month Unrestricted access to data (local/global) Poor Real-World Modeling. Objects composed of: Attributes Behavior 2/10/2018 Assoc. Prof. Stoyan Bonev
The 3 main OOP characteristics Data Encapsulation/Data Hiding Data and its functions are said to be encapsulated into a single entity. Data is concealed within a class, so that it cannot be accessed mistakenly by functions outside the class. Inheritance Polymorphism 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev OOP terminology Member functions are referred to as methods. Data items are referred to as attributes or instance variables. Calling an object’s member function is referred to as sending a message to the object, i.e. making the object to do some job. 2/10/2018 Assoc. Prof. Stoyan Bonev
Candidates to become objects Physical objects Elements of computer-user environment Data-storage constructs Human entities Collections of data User-defined data types Components of computer games Other 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Physical objects Automobiles, Countries, Aircrafts, Electrical components. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Elements of computer-user environment Windows like forms, frames, panels etc Resources – elements of user interface like button, label, edit box, list box, combo box, menu, radio button, check box etc. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Data-storage (container) structures Array, Stack, Queue, List, Binary tree etc. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Human entities Employees, Managers, Scientists, Students, Instructors, Professors etc. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Collections of data An inventory, A personnel file, A dictionary, Specific tables etc. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects User-defined data types Time, Date, Dimension, 2D Point, 3D Point. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Components of computer games Cars in auto race, Players, Opponents, Friends. 2/10/2018 Assoc. Prof. Stoyan Bonev
Kinds of things to become objects Other Anything limited by your imagination. OR the big advantage of OOP style, OR the big challenge of OOP style. 2/10/2018 Assoc. Prof. Stoyan Bonev
The Concept of Abstraction Abstraction is a view or representation of an entity that includes only the most significant attributes ignoring all the non significant attributes. Abstraction is a tool (weapon) against complexity in programming; its purpose is to simplify programming process. The two fundamental kinds of abstraction in modern Programming Languages: process abstraction; data abstraction. 2/10/2018 Assoc. Prof. Stoyan Bonev
Process abstraction – identified with routine concept All subroutines are process abstractions because they provide a way for a program to specify that some process is to be done without providing the details of how it is to be done. Example: Need to sort an array of numeric data Solution: sortInt(list,listLen); The call stmt is an abstraction of the sorting process Essential attributes: array name, data type & size. Non essential attribute: the sorting algorithm. 2/10/2018 Assoc. Prof. Stoyan Bonev
Process abstraction – identified with routine concept “Properly designed functions permit to ignore how a job’s done. Knowing what is done is sufficient.” B.Kernighan & D.Ritchie “A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation.” 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Evolution – next step The appearance and evolution of data abstraction necessarily follows (or used to follow) that of process abstraction because an integral and central part of every data abstraction is its operations, which are defined as process abstractions. 2/10/2018 Assoc. Prof. Stoyan Bonev
Data abstraction - intro An abstract data type, simply formulated, is encapsulation that includes only: the data representation of one specific data type and the subprograms that provide the operations for that type. Program units that use an abstract data type can declare variables of that type. An instance of an abstract data type is called an object. 2/10/2018 Assoc. Prof. Stoyan Bonev
Floating-Point as an Abstract Data Type All built-in data types like integer and real numbers may be considered as abstract data types, although they are rarely called that. Most languages include the possibility to create variables (integer and/or real) and provide a set of arithmetic operations for manipulating objects of that type. Floating-point types in HLL employ a key concept in data abstraction: information hiding. The actual format of a FP memory cell is hidden from the user. The only operations available are those provided by the language. 2/10/2018 Assoc. Prof. Stoyan Bonev
User-Defined Abstract Data Types A user-defined abstract data type should provide the same characteristics provided by language-defined types, such as FP type. Here is a list of most important characteristics: 1/ a type definition that allows program units to declare variables of the type but hides the internal representation of these variables; 2/ a set of operations for manipulating objects of the type. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Example: the stack ADT Given: stack ADT with following operations: create(stack), destroy(stack), empty(stack), push(stack, element), pop(stack), top(stack) A client of the stack ADT could have a code: create(stk1); push(stk1,color1); push(stk1,color2); if (!empty(stk1)) temp = pop(stk1); No need to change the code above in case the stack ADT implementation is modified from adjacency representation to linked list representation for example. Of course, a change in protocol of any of the operations would require changes in the clients. 2/10/2018 Assoc. Prof. Stoyan Bonev
Language Examples: C++ Remark: OOP concept For easier and better understanding of COS221 Fundamental Data Structures 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev PL examples: ADT in C++ In order to support ADT, C++ provides two constructs, that are similar to each other: class (includes data and routines to process that data) struct (used when only data is included - ???) The data defined in a C++ class are called data members. The functions (also called methods) defined in a class are called member functions. A C++ class can contain both hidden and visible entities (hidden from clients or visible to clients of the class). Information hiding: Hidden entities are placed in a private clause. Visible entities are placed in a public clause. 2/10/2018 Assoc. Prof. Stoyan Bonev
PL examples: ADT in Java Java support for ADT is like that of C++ with some important differences: All user-defined data types in Java are classes (no structs in Java), and all objects are allocated from the heap and accessed through reference variables. Subprograms (methods) in Java can only be defined in classes. So one cannot have function headers in Java classes with the corresponding function definition stored elsewhere. Therefore, a JAVA ADT is both declared and defined in a single syntactic unit. No need of destructor, obviated by Java garbage collection. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev PL examples: ADT in C# 1/ C# access modifiers are private, public, protected. Two more: internal and protected internal. They are applied to a larger encapsulation construct than class: the assembly. An assembly is a collection of files that appears to application programs to be a single DLL or an executable (EXE). An internal member of a class is visible to all classes in the assembly, in which it appears. 2/ Like Java, all C# classes are heap dynamic. Default constructors are available for all classes and they provide typical initial values (0 for integer, false for boolean). 3/ C# uses garbage collection for most of its heap objects and destructors are rarely used. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev C# (continuation) C# provides properties, borrowed from Delphi, as a way of implementing getters and setters without requiring explicit memory calls. Properties provide implicit access to specific private instance data. 2/10/2018 Assoc. Prof. Stoyan Bonev
Language Examples: C++ From Structured Programming to OO Programming. Classes/Objects in C++: Specifying the Class. Using the Class. Defining objects. Calling member functions; C++ objects as physical objects (classes SmallObj, Part); C++ objects as data types (class Distance); C++ objects as GP program element (classes Counter, String); Constructors and Destructors. Overloaded constructors; Objects as function arguments (dist3.AddDist1(dist1, dist2); ); Returning objects from Functions (dist4 = dist1.AddDist2(dist2); ); Member functions defined outside the class; Classes, Objects and Memory. 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ objects as Physical Objects class SmallObj OOP1aSmallObj.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Defining the Class General syntax Access qualifiers: private and public Data members Usually data is private Member functions Usually functions are public 2/10/2018 Assoc. Prof. Stoyan Bonev
Class SmallObj /obsolete style/ { private: int somedata; public: void SetData(int d) somedata = d; } void ShowData() cout << "\nData is =" << somedata; }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Using the Class Defining Objects Calling Member Functions (sending messages) 2/10/2018 Assoc. Prof. Stoyan Bonev
Class SmallObj /driver program/ void main() { SmallObj s1, s2; s1.SetData(67); s2.SetData(123); s1.ShowData(); s2.ShowData(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
SmallObj – UML class diagram SmallObj SmallObj somedata -somedata SetData(int) +SetData(int) ShowData() +ShowData() 2/10/2018 Assoc. Prof. Stoyan Bonev
SmallObj – UML class diagram after G.Booch cloud form SmallObj SmallObj somedata -somedata SetData(int) +SetData(int) ShowData() +ShowData() 2/10/2018 Assoc. Prof. Stoyan Bonev
SmallObj – UML object diagrams Unlike classes, objects are underlined. Colon ( : ) serves to separate the object name and the class name. s1:SmallObj somedata=15 s2:SmallObj somedata=173 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ objects as Physical Objects class Part OOP1bSparePart.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Class Part /obsolete style/ { private: int modelnumber, partnumber; float cost; public: void SetPart(int mn, int pn, float cs) modelnumber = mn; partnumber = pn; cost = cs; } void ShowPart() cout << "modelnumber=" << modelnumber << " " << "partnumber=" << partnumber << " " << "cost=" << cost; }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Class Part /driver program/ void main() { Part p1, p2; p1.SetPart(6244, 317, 21.68); p2.SetPart(8124, 516, 314.52); cout << "\n\nPart components: "; p1.ShowPart(); cout << "\n\nPart components: "; p2.ShowPart(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
Class Part /obsolete style + modern version/ { private: int modelnumber, partnumber; double cost; // modern model public: void setModelNumber(int mdl) { modelnumber = mdl; } int getModelNumber() const { return modelnumber; } void setPartNumber(int mdl) { partnumber = mdl; } int getPartNumber() const { return partnumber; } void setCost(double cst) { cost = cst; } double getCost() const { return cost; } // obsolete model public: void SetPart(int mn, int pn, float cs) { modelnumber=mn; partnumber=pn; cost=cs; } void ShowPart() { cout << "modelnumber=" << modelnumber << " " << "partnumber=" << partnumber << " " << "cost=" << cost; } }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Class Part /driver program/ void main() { Part p1, p2; p1.SetPart(6244, 317, 21.68); cout << "\nPart components: "; p1.ShowPart(); p2.setModelNumber(8124); p2.setPartNumber(516); p2.setCost(314.52); cout << "\nPart components:" << p2.getModelNumber() << " " << p2.getPartNumber() << " " << p2.getCost(); system("pause"); } 2/10/2018 Assoc. Prof. Stoyan Bonev
Class Part /modern style only/ { private: int modelnumber; int partnumber; double cost; // modern model public: void setModelNumber(int mdl) { modelnumber = mdl; } int getModelNumber() const { return modelnumber;} void setPartNumber(int mdl) { partnumber = mdl; } int getPartNumber() const { return partnumber;} void setCost(double cst) { cost = cst; } double getCost() const { return cost;} }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Class Part /driver program/ void main() { Part p2; p2.setModelNumber(8124); p2.setPartNumber(516); p2.setCost(314.52); cout << "\nPart components: " << p2.getModelNumber() << " " << p2.getPartNumber() << " " << p2.getCost(); cout << '\n' << '\n'; system("pause"); } 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Classes SmallObj, Part class SmallObj OOP1aSmallObj.cpp class Part OOP1bSparePart.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Modern building concept Until now, we have only presented parts of or very small programs which could easily be handled in one file. However, greater projects, should be split into manageable pieces, often called modules. Modules are implemented in separate files and here is a brief discussion how modularization is done in C and C++. This discussion is based on UNIX and the GNU C++ compiler. If you are using other constellations the following might vary on your side. This is especially important for those who are using IDEs. Roughly speaking, modules consist of two file types: interface descriptions and implementation files. To distinguish these types, a set of suffixes is used for C/C++ programs. 2/10/2018 Assoc. Prof. Stoyan Bonev
Table 9.2: Extensions and file types 2/10/2018 Assoc. Prof. Stoyan Bonev
Modern building concept The SmallObj class Implementation using interface file, implementation file and application file interface file OOP1am.h implementation file OOP1am.cpp application – client program OOp1amClient.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev interface file OOP1am.h #ifndef OOP1AM_H // to avoid multiple definitions #define OOP1AM_H class SmallObj { private: int somedata; public: void setSomeData(int p); int getSomeData(); }; #endif 2/10/2018 Assoc. Prof. Stoyan Bonev
implementation file OOP1am.cpp #include "oop1am.h" #include <iostream> using namespace std; // implementation file oop1am.cpp void SmallObj::setSomeData(int p) { somedata = p; } int SmallObj::getSomeData() { return somedata; } 2/10/2018 Assoc. Prof. Stoyan Bonev
application – client program OOp1amClient.cpp // source text of client program using // SmallObj class library #include "oop1am.h" #include <iostream> using namespace std; void main() { SmallObj s1, s2; s1.setSomeData(67); s2.setSomeData(123); cout<<“\ns1 data:”<<s1.getSomeData(); cout<<“\ns2 data:”<<s2.getSomeData(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ objects as Data Types class Distance OOP1cDistance.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Class Distance class Distance { private: int feet; float inches; public: void SetDist(int ft, float in) { feet = ft; inches = in; } void GetDist() { cout <<"\nEnter feet:" ; cin >> feet; cout <<"\nEnter inches:"; cin >> inches; } void ShowDist() cout <<“Feet=" << feet <<" Inches="<< inches; }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Class Distance void main () { Distance d1, d2; d1.SetDist(3, 5.6); cout << "\nDistance components: "; d1.ShowDist(); d2.GetDist(); cout << "\nDistance components: "; d2.ShowDist(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ objects as general purpose programming elements class Counter OOP1dCounter.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Class Counter class Counter { private: unsigned count; public: void SetCount(int val) { count = val; } void GetData() { cout <<"\nEnter data:"; cin >> count; } void ShowData() { cout <<"\nData count is:" << count;} void IncCount() { count++; } unsigned GetCount() { return count; } }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Class Counter void main() { Counter c1; c1.GetData(); c1.ShowData(); c1.IncCount(); c1.ShowData(); cout << "\n" << c1.GetCount(); c1.ShowData(); Counter c2; c2.SetCount(100); cout << "\n\nCounter c2 =" << c2.GetCount(); c2.IncCount(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ objects Constructors and Destructors Class Counter OOP1dCounterWithConstructors.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Constructors and Destructors Class Counter { private: unsigned count; public: Counter() { count = 0; } Counter(int val) { count = val; } void SetCount(int val) { count = val; } void GetData() { cout <<"\nEnter data:"; cin >> count;} void ShowData() { cout <<"\nData count is:" << count;} void IncCount() { count++; } unsigned GetCount() { return count; } }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Constructors and Destructors Class Counter void main() { Counter c1; c1.GetData(); c1.ShowData(); c1.IncCount(); c1.ShowData(); cout << "\n" << c1.GetCount(); c1.ShowData(); Counter c2(100); cout << "\n\nCounter c2 =" << c2.GetCount(); c2.IncCount(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
Constructors and Destructors Class Counter Comments concerning the use of IncCount() method Definition like void IncCount() { count++; } Is helpful in statements like Counter c1; c1.IncCount(); BUT How to proceed in case we need statements like Counter c1(100), c2; c2=c1.IncCount(); Solution is to modify the IncCount() method introducing return data type Counter IncCount() { count++; return Counter(count); } Counter IncCount() { Counter temp; count++; temp.count = count; return temp; } 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ objects Constructors and Destructors class Distance OOP1cDistanceWithConstructors.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Constructors and Destructors Class Distance private: int feet; float inches; public: Distance() { feet = 0; inches = 0.0; } Distance(int ft, float in) { feet = ft; inches = in; } void SetDist(int ft, float in) { feet = ft; inches = in; } void GetDist() { cout <<"\nEnter feet:" ; cin >>feet; cout <<"\nEnter inches:"; cin >> inches; } void ShowDist() { cout <<“Feet=" << feet <<" Inches="<< inches; }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Constructors and Destructors Class Distance void main () { Distance d1, d2; d1.SetDist(3, 5.6); cout << "\nDistance components: "; d1.ShowDist(); d2.GetDist(); cout << "\nDistance components: "; d2.ShowDist(); Distance d3, d4(7, 8.9); cout << "\nDistance components: "; d3.ShowDist(); cout << "\nDistance components: "; d4.ShowDist(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
Objects as Function Arguments Digression on how to add two Distances In feet/inches (1 foot = 12 inches) Example 1: d1(5, 6.3), d2(10, 2.1), d3 d3 = d1 + d2 = 15 feet, 8.4 inches Example 2: d1(5, 11.3), d2(10, 2.1), d3 d3 = d1 + d2 = 15 feet,13.4 inches or 16 feet, 1.4 inches (if normalize) 2/10/2018 Assoc. Prof. Stoyan Bonev
Objects as Function Arguments Class Distance Distance dist1(5, 6.8), dist2(3, 4.5), dist3; Task: To add two distances using a method: dist3.AddDist1(dist1, dist2); OOP1eAddDistance1.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev 66
Assoc. Prof. Stoyan Bonev 2/10/2018 Assoc. Prof. Stoyan Bonev
Objects as Function Arguments // void AddDist1(Distance d1, Distance d2); // void AddDist1(Distance d1, Distance d2) { feet = d1.feet +d2.feet; inches = d1.inches + d2.inches; if (inches >= 12.) inches -= 12.; feet++; } 2/10/2018 Assoc. Prof. Stoyan Bonev
Objects as Function Arguments // Alternate version // Member function defined outside the class // using scope resolution operator void Distance::AddDist1(Distance d1, Distance d2) { feet = d1.feet +d2.feet; inches = d1.inches + d2.inches; if (inches >= 12.) inches -= 12.; feet++; } 2/10/2018 Assoc. Prof. Stoyan Bonev
Returning Objects from Functions Class Distance Distance dist1(5, 6.8), dist2(3, 4.5), dist4; Task: To add two distances using alternate method: dist4 = dist1.AddDist2(dist2); OOP1fAddDistance2.cpp 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev 2/10/2018 Assoc. Prof. Stoyan Bonev
Returning Objects from Functions // first version of source text Distance AddDist2(Distance d1) { Distance temp; temp.feet = feet + d1.feet; temp.inches = inches + d1.inches; if (temp.inches >= 12.) temp.inches -= 12.; temp.feet++; } return temp; 2/10/2018 Assoc. Prof. Stoyan Bonev
Returning Objects from Functions // second alternate version of source text Distance AddDist2(Distance d1) { int ft; float in; ft = feet + d1.feet; in = inches + d1.inches; if (in >= 12.) in -= 12.; ft++; } return Distance(ft, in); // anonymous, nameless object 2/10/2018 Assoc. Prof. Stoyan Bonev
Member functions defined outside the class :: scope resolution operator 2/10/2018 Assoc. Prof. Stoyan Bonev
Structures and Classes May use in almost exactly the same way The only formal difference: In class: the members are private by default In struct: the members are public by default 2/10/2018 Assoc. Prof. Stoyan Bonev
Classes, Objects and Memory All the objects in a given class use the same member functions. All the objects in a given class use their own unique data components. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev 2/10/2018 Assoc. Prof. Stoyan Bonev
Classes, Objects and Memory If a data item in a class is defined static, then only one such an item is created, no matter how many objects there are. 2/10/2018 Assoc. Prof. Stoyan Bonev
Classes, Objects and Memory 2/10/2018 Assoc. Prof. Stoyan Bonev
Use of static class data – separate declaration and definition class foo { private: static int count; // declaration only public: foo() { count++; } int getcount() { return count; } }: int foo::count = 0; // definition void main() foo f1, f2, f3; cout << ‘\n’ << count; } 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev const and Classes const Member Functions guarantee they will never modify its class member data class aClass { private: int alpha; public: void nonFunc() // non const function { alpha = 99; } // OK void conFunc() const // const member fun { alpha = 999; } // ERROR }; 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev const and Classes const Objects When an object is declared as const, it can not be modified. It follows that only const member functions can be used with it, because they are the only ones that guarantee not to modify the object. Example: Lafore, pp 255 2/10/2018 Assoc. Prof. Stoyan Bonev
Evolution of the class concept Methods whose type is like ShowData() are considered obsolete and therefore not recommended to be used. Instead, a pair of methods associated to each one of the data fields is introduced. They serve for bi-directional (in, out) access to the data field. Method Accessor, also ‘getter’ (getX()) Method Mutator, also ‘setter’ (setX()) Microsoft extends the getX/setX methods to the property concept 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ Modern Object – native code class ModernObject { private: int x; public: ModernObject() { x = 0; } // constructors public: ModernObject(int par) { x = par; } // obsolete method Show...type() public: void showModernObject() { cout << endl << "Data = " << x ; } // method accessor public: int getModernObject() { return x; } // methods mutators public: void setModernObject(int par) { x = par; } public: void setModernObject(int par1, int par2) { x = par1 + par2; } public: void setModernObject(int par1, int par2, int par3) { x = par1 + par2 + par3; } // property // properties not supported in native code // end of property }; // end of class ModernObject 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ Modern Object – native code void main() { ModernObject a; ModernObject b(15); ModernObject c; a.showModernObject(); b.showModernObject(); // test accessor and mutators methods c.setModernObject(20); cout << endl << c.getModernObject(); c.setModernObject(20,50); cout << endl << c.getModernObject(); c.setModernObject(20,30,40); cout << endl << c.getModernObject(); /* // test property // no properties, =>> ,no statements to test properties */ } 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ Modern Object – managed code using namespace System; __gc class ModernObject { private: int x; public: ModernObject() { x = 0; } // constructors public: ModernObject(int par) { x = par; } // obsolete metod Show...type() public: void showModernObject() { Console::Write("Data = "); Console::WriteLine(x) ; } // method accessor public: int getModernObject() { return x; } // methods mutators public: void setModernObject(int par) { x = par; } public: void setModernObject(int par1, int par2) { x = par1 + par2; } public: void setModernObject(int par1, int par2, int par3) { x = par1 + par2 + par3; } // property PropertyX public: __property int get_PropertyX() { return x; } public: __property void set_PropertyX(int par) { x = par; } }; 2/10/2018 Assoc. Prof. Stoyan Bonev
C++ Modern Object – managed code void main( ) { ModernObject *a = new ModernObject(); ModernObject *b = new ModernObject(15); ModernObject *c = new ModernObject(); a->showModernObject(); b->showModernObject(); // test accessor and mutators methods c->setModernObject(20); Console::WriteLine( c->getModernObject() ); c->setModernObject(20,50); Console::WriteLine( c->getModernObject() ); c->setModernObject(20,30,40); Console::WriteLine( c->getModernObject() ); // test property ModernObject *f = new ModernObject(24); Console::WriteLine(f->getModernObject()); // test get property Console::WriteLine(f->PropertyX); // test set property and get property f->PropertyX = 135; Console::WriteLine(f->PropertyX); Console::ReadLine(); } 2/10/2018 Assoc. Prof. Stoyan Bonev
More on OOP Data Encapsulation Data Encapsulation in VBasic See file Oop1GetSet.vb Data Encapsulation in C# See file Oop1fGetSet.cs Data Encapsulation in Java See file Oop1fGetSet.java 88
C# Modern Object –get(), set(), properties class ModernObject { private int x; public ModernObject() { x = 0; } // constructors public ModernObject(int par) { x = par; } // method accessor public int getModernObject() { return x; } // methods mutators public void setModernObject(int par) { x = par; } public void setModernObject(int par1, int par2) { x = par1 + par2; } public void setModernObject(int par1, int par2, int par3) { x = par1 + par2 + par3; } public int PropertyX // property { get return x; } set x = value; } // end of property } // end of class ModernObject 2/10/2018 Assoc. Prof. Stoyan Bonev
C# Modern Object –get(), set(), properties class Program { static void Main(string[] args) ModernObject a = new ModernObject(); ModernObject b = new ModernObject(15); ModernObject c = new ModernObject(); // test accessor and mutators methods c.setModernObject(20); Console.WriteLine(" {0}", c.getModernObject()); c.setModernObject(20, 50); Console.WriteLine(" " + c.getModernObject()); c.setModernObject(20, 30, 40); Console.WriteLine(" " + c.getModernObject()); ModernObject f = new ModernObject(115); Console.WriteLine(" " + f.getModernObject()); f.setModernObject(125); Console.WriteLine(" " + f.getModernObject()); // test get property Console.WriteLine(" " + f.PropertyX); // test set property and get property f.PropertyX = 135; Console.WriteLine(" " + f.PropertyX); } // end of Main } // end of class Program 2/10/2018 Assoc. Prof. Stoyan Bonev
Language Examples: C# (continued) Common solution to need for access to data members: accessor methods (getter) and mutator methods (setter) C# provides properties as a way of implementing getters and setters without requiring explicit method calls 2/10/2018 Assoc. Prof. Stoyan Bonev Source: Longman dictionary 1987 91
Assoc. Prof. Stoyan Bonev 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; 2/10/2018 Assoc. Prof. Stoyan Bonev Source: Longman dictionary 1987 92
Java Modern Object –get(), set() class ModernObject { private int x; public ModernObject() { x = 0; } public ModernObject(int par) { x = par; } // method accessor public int getModernObject() { return x; } // methods mutators public void setModernObject(int par) { x = par; } public void setModernObject(int par1, int par2) { x = par1 + par2; } public void setModernObject(int par1, int par2, int par3) { x = par1 + par2 + par3; } } // end of class ModernObject public class ModernObjectProg1 { public static void main(String[] args) { ModernObject a = new ModernObject(); ModernObject b = new ModernObject(15); ModernObject c = new ModernObject(); ModernObject d = new ModernObject(); // test accessor and mutators methods c.setModernObject(20); System.out.println(" " + c.getModernObject() ); c.setModernObject(20,50); System.out.println(" " + c.getModernObject() ); c.setModernObject(20,30,40); System.out.println(" " + c.getModernObject() ); } // end of method main() } // end of class ModernObjectProg1 2/10/2018 Assoc. Prof. Stoyan Bonev
Java Modern Object –get(), set() No property concept supported in Java. 2/10/2018 Assoc. Prof. Stoyan Bonev
Exercises OOP. Data Encapsulation Coming slides include problem tasks to be solved at the OOP practical session. 2/10/2018 Assoc. Prof. Stoyan Bonev
Exercises OOP. Data Encapsulation Test all programs discussed in the lecture. Build own programs illustrating the concept of classes and objects. Assignments under discussion are based on lecture 21. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Demo programs oop1aSmallObj.cpp, oop1am.h interface file oop1am.cpp implementation file oop1amClient.cpp client program file oop1bSparePart.cpp, oop1cDistence.cpp, oop1cDistanceWithConstructors.cpp, oop1dCounter.cpp, oop1dCounterWithConstructors.cpp, oop1eAddDistance1.cpp, oop1fAddDistance2.cpp, 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Tasks Task 1. Test and modify programs for the SmallObj, Part, Counter, and Distance classes. 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Tasks Task 2. Build a class Circle with two constructors, data member for radius, getter and setter methods and methods that return the area and perimeter of the circle 2/10/2018 Assoc. Prof. Stoyan Bonev
Assoc. Prof. Stoyan Bonev Tasks Task 3. Build a class Person with data components and member functions to present name(s), e-mail address, id number, age and gender of an AUBG student. 2/10/2018 Assoc. Prof. Stoyan Bonev
Abstract Data Types and Encapsulation Concepts Chapter 11 Abstract Data Types and Encapsulation Concepts Source: Longman dictionary 1987 101
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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-102 Source: Longman dictionary 1987 102
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-103 Source: Longman dictionary 1987 103
Introduction to Data Abstraction An abstract data type is a user-defined data type that satisfies the following two conditions: The representation of, and operations on, objects of the type are defined in a single syntactic unit 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-104 Source: Longman dictionary 1987 104
Advantages of Data Abstraction Advantage of the first condition Program organization, modifiability (everything associated with a data structure is together), and separate compilation Advantage the second 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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-105 Source: Longman dictionary 1987 105
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-106 Source: Longman dictionary 1987 106
Design Issues What is the form of the container for the interface to the type? Can abstract types be parameterized? What access controls are provided? Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-107 Source: Longman dictionary 1987 107
Language Examples: Ada The encapsulation construct is called a package Specification package (the interface) Body package (implementation of the entities named in the specification) Information Hiding The spec package has two parts, public and private The name of the abstract type appears in the public part of the specification package. This part may also include representations of unhidden types The representation of the abstract type appears in a part of the specification called the private part More restricted form with limited private types Private types have built-in operations for assignment and comparison Limited private types have NO built-in operations Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-108 Source: Longman dictionary 1987 108
Language Examples: Ada (continued) Reasons for the public/private spec package: 1. The compiler must be able to see the representation after seeing only the spec package (it cannot see the private part) 2. Clients must see the type name, but not the representation (they also cannot see the private part) Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-109 Source: Longman dictionary 1987 109
Language Examples: Ada (continued) Having part of the implementation details (the representation) in the spec package and part (the method bodies) in the body package is not good One solution: make all ADTs pointers Problems with this: 1. Difficulties with pointers 2. Object comparisons 3. Control of object allocation is lost Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-110 Source: Longman dictionary 1987 110
An Example in Ada package Stack_Pack is type stack_type is limited private; max_size: constant := 100; function empty(stk: in stack_type) return Boolean; procedure push(stk: in out stack_type; elem:in Integer); procedure pop(stk: in out stack_type); function top(stk: in stack_type) return Integer; private -- hidden from clients type list_type is array (1..max_size) of Integer; type stack_type is record list: list_type; topsub: Integer range 0..max_size) := 0; end record; end Stack_Pack Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-111 Source: Longman dictionary 1987 111
Language Examples: C++ Based on C struct type and Simula 67 classes The class is the encapsulation device 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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-112 Source: Longman dictionary 1987 112
Language Examples: C++ (continued) Information Hiding Private clause for hidden entities Public clause for interface entities Protected clause for inheritance (Chapter 12) Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-113 Source: Longman dictionary 1987 113
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-114 Source: Longman dictionary 1987 114
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-115 Source: Longman dictionary 1987 115
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 num) {…}; void pop () {…}; int top () {…}; int empty () {…}; } Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-116 Source: Longman dictionary 1987 116
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 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(); } Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-117
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-118
Evaluation of ADTs in C++ and Ada C++ support for ADTs is similar to expressive power of Ada Both provide effective mechanisms for encapsulation and information hiding Ada packages are more general encapsulations; classes are types Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-119 Source: Longman dictionary 1987 119
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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-120 Source: Longman dictionary 1987 120
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-121 Source: Longman dictionary 1987 121
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-122 Source: Longman dictionary 1987 122
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-123 Source: Longman dictionary 1987 123
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-124 Source: Longman dictionary 1987 124
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-125 Source: Longman dictionary 1987 125
Abstract Data Types in Ruby (continued) class StackClass { def initialize @stackRef = Array.new @maxLen = 100 @topIndex = -1 end def push(number) … end def pop … end def top … end def empty … end Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-126 Source: Longman dictionary 1987 126
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-127 Source: Longman dictionary 1987 127
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, and Ruby Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-128 Source: Longman dictionary 1987 128
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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-129 Source: Longman dictionary 1987 129
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-130 Source: Longman dictionary 1987 130
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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-131 Source: Longman dictionary 1987 131
C# Assemblies A collection of files that appear 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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-132 Source: Longman dictionary 1987 132
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 © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-133 Source: Longman dictionary 1987 133
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 Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-134 Source: Longman dictionary 1987 134
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 - Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-135 Source: Longman dictionary 1987 135
Support for Object-Oriented Programming Chapter 12 Support for Object-Oriented Programming Source: Longman dictionary 1987 136
Allocation and DeAllocation of Objects From where are objects allocated? If they behave line the ADTs, they can be allocated from anywhere Allocated from the run-time stack Explicitly create on the heap (via new) If they are all heap-dynamic, references can be uniform thru a pointer or reference variable Simplifies assignment - dereferencing can be implicit If objects are stack dynamic, there is a problem with regard to subtypes Is deallocation explicit or implicit? Copyright © 2009 Addison-Wesley. All rights reserved. Copyright © 2009 Addison-Wesley. All rights reserved. 1-137 Source: Longman dictionary 1987 137
Thank You For Your Attention