1 / 120

UNIT IV OBJECT-ORIENTATION, CONCURRENCY, AND EVENT HANDLING

UNIT IV OBJECT-ORIENTATION, CONCURRENCY, AND EVENT HANDLING. Object-Oriented Programming. Think from the perspectives of data (“things”) and their interactions with the external world Object Data Method: interface and message Class The need to handle similar “things”

llollis
Download Presentation

UNIT IV OBJECT-ORIENTATION, CONCURRENCY, AND EVENT HANDLING

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. UNIT IV OBJECT-ORIENTATION, CONCURRENCY, AND EVENT HANDLING IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  2. Object-Oriented Programming • Think from the perspectives of data (“things”) and their interactions with the external world • Object • Data • Method: interface and message • Class • The need to handle similar “things” • American, French, Chinese, Korean  abstraction • Chinese: northerners, southerners  inheritance • Dynamic binding, polymorphism IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  3. What OOP Allows You? • You analyze the objects with which you are working (attributes and tasks on them) • You pass messages to objects, requesting them to take action • The same message works differently when applied to the various objects • A method can work with different types of data, without the need for separate method names • Objects can inherit traits of previously created objects • Information can be hidden better IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  4. Abstraction • Two types of abstractions: • Process abstraction: subprograms • Data abstraction • Floating-point data type as data abstraction • The programming language will provide (1) a way of creating variables of the floating-point data type, and (2) a set of operators for manipulating variables • Abstract away and hide the information of how the floating-point number is presented and stored • Need to allow programmers to do the same • Allow them to specify the data and the operators IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  5. Abstraction Data Type • Abstract data type: a user-defined data type • Declaration of the type and protocol of operations on objects of the type, i.e., type’s interface, are defined in a syntactic unit; interface indep. of implementation • Representation of objects of the type is hidden from program units that use these objects; only possible operations are those provided in type's definition class data type int object variable i, j, k method operators +, -, *, / y = stack1.top()+3; vs y = (-x) + 3; IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  6. Advantages of Data Abstraction • Advantage of having interface independent of object representation or implementation of operations: • Program organization, modifiability (everything associated with a data structure is together), separate compilation • Advantage of 2nd condition (info. hiding) • Reliability: By hiding 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 IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  7. Language Requirements for ADTs • A syntactic unit to encapsulate type definition • A method of making type names and subprogram headers visible to clients, while hiding actual definitions • Some primitive operations that are built into the language processor • Example: an abstract data type for stack • create(stack), destroy(stack), empty(stack), push(stack, element), pop(stack), top(stack) • Stack may be implemented with array, linked list, ... IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  8. Abstract Data Types in 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 has own copy of class data members • Instances can be static, stack dynamic, heap dynamic • Information hiding • Private clause for hidden entities • Public clause for interface entities • Protected clause for inheritance (Chapter 12) IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  9. Implicitly inlined  code placed in caller’s code Member Functions Defined in Class 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 () {…}; } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  10. Language Examples: C++ (cont.) • 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 IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  11. Language Examples: C++ (cont.) • Destructors • Functions to clean up 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 (~) • Friend functions or classes: to allow access to private members to some unrelated units or functions • Necessary in C++ IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  12. Uses of the Stack Class void main() { int topOne; Stack stk; //create an instance of the Stack class stk.push(42); // c.f., stk += 42 stk.push(17); topOne = stk.top(); // c.f., &stk stk.pop(); ... } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  13. Member Func. Defined Separately // Stack.h - header file for Stack class class Stack { private: int *stackPtr, maxLen, topPtr; public: Stack(); //** A constructor ~Stack(); //** A destructor void push(int); void pop(); int top(); int empty(); } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  14. Member Func. Defined Separately // Stack.cpp - implementation for Stack #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;}; void Stack::push(int number) { if (topPtr == maxLen) cerr << "Error in push--stack is full\n"; else stackPtr[++topPtr] = number;} ... IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  15. Abstract Data Types in Java • Similar to C++, except: • All user-defined types are classes • All objects are allocated from the heap and accessed through reference variables • Methods must be defined completely in a class an abstract data type in Java is defined and declared in a single syntactic unit • Individual entities in classes have access control modifiers (private or public), rather than clauses • No destructor  implicit garbage collection IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  16. An Example in Java class StackClass { 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 () {…}; } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  17. An Example in Java public class TstStack { public static void main(String[] args) { StackClass myStack = new StackClass(); myStack.push(42); myStack.push(29); System.out.println(“:“+myStack.top()); myStack.pop(); myStack.empty(); } } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  18. “Hello World!” Compared C++ #include <iostream> using namespace std; int main(){ cout<<"Hello World!"<<endl; } C #include <stdio.h> int main(void){ print("Hello world!"); } Ruby puts 'Hello, world!' or class String def say puts self end end 'Hello, world!'.say Java public class HelloWorld { public static void main(String[] args){ System.out.println ("Hello world!"); } } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  19. Parameterized ADTs • Parameterized abstract data types allow designing an ADT that can store any type elements (among other things): 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 IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  20. Parameterized ADTs in C++ • Make Stack class generic in stack size by writing parameterized constructor function class Stack { ... Stack (int size) { stk_ptr = new int [size]; max_len = size - 1; top = -1; }; ... } Stack stk(150); IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  21. Parameterized ADTs in C++ (cont.) • Parameterize element type by templated classtemplate <class Type>class Stack { private: Type *stackPtr; int maxLen, topPtr; public: Stack(int size) { stackPtr = new Type[size]; maxLen = size-1; topPtr = -1; } ...Stack<double> stk(150); Instantiated by compiler IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  22. Generalized Encapsulation • Enclosure for an abstract data type defines a SINGLE data type and its operations • How about defining a more generalized encapsulation construct that can define any number of entries/types, any of which can be selectively specified to be visible outside the enclosing unit • Abstract data type is thus a special case IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  23. 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 logically related code and data into a unit that can be separately compiled (compilation units) • Such collections are called encapsulation • Example: libraries IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  24. Means of Encapsulation: 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 IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  25. 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 client programs to reference to compiled version of implementation file, which is linked as libraries IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  26. Encapsulation in C++ • Can define header and code files, similar to those of C • Or, classes can be used for encapsulation • The class header file has only the prototypes of the member functions • The member definitions are defined in a separate file  Separate interface from implementation • Friends provide a way to grant access to private members of a class • Example: vector object multiplied by matrix object IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  27. Friend Functions in C++ class Matrix; class Vector { friend Vector multiply(const Matrix&, const Vector&); ... } class Matrix { friend Vector multiply(const Matrix&, const Vector&); ... } Vector multiply(const Matrix& ml, const Vector& vl) { ... } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  28. Naming Encapsulations • Encapsulation discussed so far is to provide a way to organize programs into logical units for separate compilation • On the other hand, large programs define many global names; need a way to avoid name conflicts in libraries and client programs developed by different programmers • A naming encapsulation is used to create a new scope for names IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  29. Naming Encapsulations (cont.) • C++ namespaces • Can place each library in its own namespace and qualify names used outside with the namespace namespace MyStack { ... // stack declarations } • Can be referenced in three ways: MyStack::topPtr using MyStack::topPtr; p = topPtr; using namespace MyStack; p = topPtr; • C# also includes namespaces IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  30. Naming Encapsulations (cont.) • 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, e.g., myStack.topPtr, or use import declaration, e.g., import myStack.*; • Ada Packages • Packages are defined in hierarchies which correspond to file hierarchies • Visibility from a program unit is gained with the with clause IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  31. Naming Encapsulations (cont.) • Ruby classes are name encapsulations, but Ruby also has modules • Module: • Encapsulate libraries of related constants and methods, whose names in a separate namespace • Unlike classes  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 IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  32. Ruby Modules module MyStuff PI = 3.1415 def MyStuff.mymethod1(p1) ... end def MyStuff.mymethod(p2) ... end end Require ‘myStuffMod’ myStuff.mymethod1(x) IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  33. Support for Object-Oriented Programming IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  34. Software Productivity • Pressure on software productivity vs. continual reduction in hardware cost • Productivity increases can come from reuse • Abstract data types (ADTs) for reuse? • Mere ADTs are not enough • ADTs are difficult to reuse—always need changes for new uses, e.g., circle, square, rectangle, ... • All ADTs are independent and at the same level hard to organize program to match problem space • More, in addition to ADTs, are needed IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  35. What Are Needed? • Given a collection of related ADTs, need to factor out their commonality and put it in a new type  abstraction • The collection of ADTs then inherit from the new type and add their own • class Shape { • private: • int x; int y; • public: • Shape(int a, int b); • ... • virtual void draw(); • }; • class Circle: public Shape { • private: • int radius; • public: • Circle(int x1, y2, r1); • ... • void draw(); • }; IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  36. What Are Needed? (cont.) • For classes in an inheritance relationship, a method call may need to be bound to a specific object of one of the classes at run time Shape *shape_list[3]; // array of shape objects shape_list[0] = new Circle; shape_list[1] = new Square; shape_list[2] = new Triangle; for(int i = 0; i < 3; i++){ shape_list[i].draw(); } • Polymorphism and dynamic binding IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  37. Object-Oriented Programming • An object-oriented language must provide supports for three key features: • Abstract data types • Inheritance: the central theme in OOP and languages that support it • Polymorphism and dynamic binding • What does it mean in a pure OO program, where x, y, and 3 are objects? y = x + 3; IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  38. Object-Oriented Concepts • ADTs are usually called classes, e.g. Shape • Class instances are called objects, e.g. shape_list[0] • A class that inherits is a derived class or a subclass, e.g. Circle, Square • The class from which another class inherits is a parent class or superclass, e.g. Shape • Subprograms that define operations on objects are called methods, e.g. draw() IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  39. Object-Oriented Concepts (cont.) • Calls to methods are called messages, e.g. shape_list[i].draw(); • Object that made the method call is the client • The entire collection of methods of an object is called its message protocol or message interface • Messages have two parts--a method name and the destination object • In the simplest case, a class inherits all of the entities of its parent IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  40. Inheritance • Allows new classes defined in terms of existing ones, i.e., by inheriting common parts • Can be complicated by access controls to encapsulated entities • A class can hide entities from its subclasses (private) • A class can hide entities from its clients • A class can also hide entities for its clients while allowing its subclasses to see them • A class can modify an inherited method • The new one overrides the inherited one • The method in the parent is overridden IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  41. Inheritance (cont.) • There are two kinds of variables in a class: • Class variables - one/class • Instance variables - one/object, object state • There are two kinds of methods in a class: • Class methods – accept messages to the class • Instance methods – accept messages to objects • Single vs. multiple inheritance • One disadvantage of inheritance for reuse: • Creates interdependencies among classes that complicate maintenance IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  42. Dynamic Binding • A polymorphic variable can be defined in a class that is able to reference (or point to) objects of the class and objects of any of its descendants Shape *shape_list[3]; // array of shapes shape_list[0] = new Circle; shape_list[1] = new Square; shape_list[2] = new Triangle; for(int i = 0; i < 3; i++){ shape_list[i].draw(); } IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  43. Dynamic Binding • When a class hierarchy includes classes that override methods and such methods are called through a polymorphic variable, the binding to the correct method will be dynamic, e.g.,shape_list[i].draw(); • Allows software systems to be more easily extended during both development and maintenance, e.g., new shape classes are defined later IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  44. Dynamic Binding (cont.) • An abstract method is one that does not include a definition (it only defines a protocol) • An abstract class is one that includes at least one virtual method • An abstract class cannot be instantiated • class Shape { • private: • int x; int y; • public: • ... • virtual void draw(); • }; • class Circle: public Shape { • private: • int radius; • public: • ... • void draw() {...}; • }; IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  45. Design Issues for OOP Languages • The exclusivity of objects • Are subclasses subtypes? • Type checking and polymorphism • Single and multiple inheritance • Object allocation and deallocation • Dynamic and static binding • Nested classes • Initialization of objects IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  46. The Exclusivity of Objects • Option 1: Everything is an object • Advantage: elegance and purity • Disadvantage: slow operations on simple objects • Option 2: Add objects to existing typing system • Advantage: fast operations on simple objects • Disadvantage: confusing typing (2 kinds of entities) • Option 3: Imperative-style typing system for primitives and everything else objects • Advantage: fast operations on simple objects and a relatively small typing system • Disadvantage: still confusing by two type systems IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  47. Are Subclasses Subtypes? • Does an “is-a” relationship hold between a parent class object and an object of subclass? • If a derived class is-a parent class, then objects of derived class behave same as parent class object subtype small_Int is Integer range 0 .. 100; • Every small_Int variable can be used anywhere Integer variables can be used • A derived class is a subtype if methods of subclass that override parent class are type compatible with the overridden parent methods • A call to overriding method can replace any call to overridden method without type errors IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  48. Type Checking and Polymorphism • Polymorphism may require dynamic type checking of parameters and the return value • Dynamic type checking is costly and delays error detection • If overriding methods are restricted to having the same parameter types and return type, the checking can be static IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  49. Single and Multiple Inheritance • Multiple inheritance allows a new class to inherit from two or more classes • Disadvantages of multiple inheritance: • Language and implementation complexity: if class C needs to reference both draw() methods in parents A and B, how to do? If A and B in turn inherit from Z, which version of Z entry in A or B should be ref.? • Potential inefficiency: dynamic binding costs more with multiple inheritance (but not much) • Advantage: • Sometimes it is quite convenient and valuable IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

  50. Object Allocation and Deallocation • From where are objects allocated? • If behave like ADTs, can be allocated from anywhere • Allocated from the run-time stack • Explicitly created 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, assignment of subclass B’s object to superclass A’s object is value copy, but what if B is larger in space? • Is deallocation explicit or implicit? IFETCE/ME CSE/I YEAR/II SEM/CP7203/PPL/UNIT 4/PPT/VER 1.0

More Related