1 / 74

Coverage

Coverage. Introduction Various design issues for OOPs C++ and its support for OOP Java and its support for OOP C# and its support for OOP Ruby and its support for OOP Python and its support for OOP Differences between Java and C++ Event Handling in Java

landon
Télécharger la présentation

Coverage

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. Coverage • Introduction • Various design issues for OOPs • C++ and its support for OOP • Java and its support for OOP • C# and its support for OOP • Ruby and its support for OOP • Python and its support for OOP • Differences between Java and C++ • Event Handling in Java • Programming in Object Oriented Languages OOP

  2. Introduction • Motivation for Object Oriented Languages: • Encapsulate and reuse programs and data structures • Inheritance paved way for reusability • Reuse should provide extension (add new methods or entities), restriction (derivation restricted to a specific group) and partially redefined (certain components can be changed) • Also support polymorphism (with generic data structures) and abstraction • Imperative languages does not posses the option of controlling the use of global variables. • Object Oriented Programming types: • OOP is an added feature to the language: • C++ is called as relative OOP as you can write non-object oriented programs as well • Ada supports procedural and data-oriented programming • Language supports OOP but appearance and basic structure is similar to that of imperative languages • Java is based on C++ OOP

  3. Introduction • Object Oriented Programming types: • Pure OOP languages: • Supports the following: • Encapsulation and Information hiding • Inheritance • Polymorphism and Dynamic Binding • All pre-defined types in the language are objects • All user-defined types are also objects • Any operation required is handled by sending messages to objects • Example: Smalltalk, Eiffel, Ruby • Different paradigms evolved as procedural (in 1950s to 1970s), data-oriented (in early 1980s) and Object Oriented Programming (in late 1980s) OOP

  4. Introduction • Abstraction • Process of making complex stuff simple by providing appropriate classes to represent those complex entities • Classes provide abstraction of a thing (object) which contains the characteristics (attributes) and the behaviour (methods) • Data Abstraction: encapsulation mechanism to limit both the scope and the visibility of the data values and functions defined for the values • Process Abstraction: • The way to say what has to be done and not how to do it • Many sort methods are available in many languages which hide the implementation of the sorting algorithm • Abstract Data Types • Process of creating new objects and hiding its representation from the program units that use them • Actual implementation is not made known to the user but users can use the implementation • Ex. int in Java – representation is hidden and operations are builtin OOP

  5. Classes and Objects Class: Most common abstract data type Class instances are called as objects A class that inherits is called a derived class or a subclass The class from which another class inherits is called as a parent class or superclass A class which is within a class is called as inner class Subprograms that define operations on objects are called as methods Calls to methods are called as messages, which are made up of a method name and destination object Type checking (for methods) is done at compile-time in statically-typed languages like Java and checking is done at run-time in dynamically checked languages like Smalltalk All the methods of an object are jointly called as message protocol or message interface. A class can be made up of two types of variables: class variable which is one per class and instance variable which is one per object Java: class and array are the only two structured types 5 OOP

  6. C++ type checking example #include <iostream> using namespace std; class baseclass { public: baseclass() { x = 0; cout << "Base class constructor" << endl;} private: int x; // private variable }; class subclass: public baseclass // inheritance { public: subclass() { s = 0; cout << "Subclass constructor" << endl;} private: int s; }; int main() { baseclass e; // calls the base class constructor subclass s; // calls both base class and sub class constructors e = (baseclass) s; // is allowed // e = s; // is allowed and same as previous statement // s = (subclass) e; // Compilation error - not allowed } 6 OOP

  7. Encapsulation Technique of packaging things together so as to form a well-defined programming unit By packaging things, encapsulation isolates the operational details of a procedure from its usage For example, integer type hides the internal structure of integer and also does not permit the user from manipulating the bits Encapsulation Constructs: Divide large programs into small programs called as Modules. Subprograms that are logically related are grouped but separately compiled called as compilation units Naming Encapsulation: Divide large programs into many global names based on logical groupings. Ex. C++ Namespaces and Java Packages Encapsulation in C: Interface is placed in a header file. Encapsulation in C++: Similar to C. Friend functions can access private members of the friend class. Encapsulation in C#:C# Assembly provides the concept of combining many files into one single executable file or a dynamic link library. Encapsulation in Ruby: Ruby has modules which are used to encapsulate methods and constants. 7 OOP

  8. Introduction Information Hiding: Provide the interface to reveal only those that ought to be revealed Different from Encapsulation: In Encapsulation: packaging makes the information hidden In Information Hiding: Only interface is provided and thus hiding information. Constructor Memory allocation and initialization is done by constructor They do not create instances Implicitly called Same name as class, with or without parameters Constructor without parameters is called as default constructor C++: Parameterless constructor is given by default if no constructor is specified. Destructor Used to clean or reclaim heap storage Implicitly called when the object lifetime ends Has the same name as class but with a tilde preceded Must be parameterless 8 OOP

  9. Inheritance Access controls on encapsulated entities can hide entities Code reuse is provided by inheritance public class test { public int a; // instance variables of the class. public test( ) { … } // constructor of the class. // methods specified in the class. public <type> functionname ( parameters ) { … } } int main ( ) { test y; // This part is the client of the class as it uses the class. // y is an object or instance of the class. } 9 OOP

  10. Inheritance Single and Multiple Inheritance If a subclass inherits from only one parent class, then it uses single inheritance If a subclass inherits from more than one parent class, then it uses multiple inheritance Multiple inheritance might have name collisions Classes B and C are derived from the common parent A. Also, class D has both B and C as parents. This kind of setup is called as diamond or shared inheritance. If a method is defined both in B and C, then which one does class D derives? 10 OOP

  11. Polymorphism When a class hierarchy includes classes that override methods and such overridden methods are called through a polymorphic variable (or assignment polymorphism), the binding to the correct method must be handled dynamically. Example: ParentClass sampleobject = new ChildClass(); Pure Polymorphism: A single function can be applied to varied type of arguments Inclusion Polymorphism or Overriding: Child class has the function with the same signature as that of the parent class Subtype Polymorphism: Operations of one type can be applied to another Sometimes, Pure polymorphism is also called as Subtype polymorphism. Alternatively, Inclusion polymorphism is also called as Subtype polymorphism 11 OOP

  12. Polymorphism 12 OOP

  13. Polymorphism Adhoc Polymorphism or overloading Different functions are denoted with same name but with different signatures Parametric Polymorphism Type of the parameters is unspecified in the declaration Ex. Ada Generic, C++ Template #include <iostream> using namespace std; template <typename T> T max(T x, T y) { return x > y ? x : y; } int main() { int i = 1 ,j = 2; cout << max(i,j) << endl; // Prints 2 float a = 2.0, b = 3.0; cout << max(a,b) << endl; // Prints 3 string s = "abc", t = "def"; cout << max(s,t) << endl; // Prints def return 0; } 13 OOP

  14. Polymorphism 14 OOP

  15. Introduction Type checking and Polymorphism Type checking between formal and actual parameters is vital Dynamic error checking is costly and delays error detection Abstract Method and Class An abstract method is one that does not include the implementation of the method but has the protocol (definition) An abstract class is one that includes at least one abstract method. It cannot be instantiated Abstract methods are sometimes called deferred and a class that has a deferred method is called a deferred class. It is called so because the implementation is deferred until a subclass defines it 15 OOP

  16. Introduction Various Class types: Data Manager Classes: The data managed is either called as data or state. Data Manager Classes maintain data or state information. Data Sinks or Data Sources Classes: Generates data like a random number generator but does not hold the data for any period of time. View or Observer Classes: Displays the information on an output device such as a terminal screen. Facilitator or Helper Classes: Used to do complex tasks but has very minimal or no state information themselves. 16 OOP

  17. Exceptions An Exception is any unexpected or infrequent event which is raised and thrown, during runtime. An execution handler is a procedure or code sequence that is designed to be executed when a particular exception is raised. An exception handler is said to handle or catch an exception. Exception handler might cause the program to be continued (called as resumption model) or terminated (called as termination model). Resumption model: the process of returning back through function calls to the caller during the search for a handler is called call unwinding or stack unwinding Generally, languages support termination model C language: No exception handling 17 OOP

  18. Exceptions Synchronous exception is caused by errors that the programs can definitely catch Asynchronous exception is something that could happen any time and might be due to failure of hardware devices or memory allocation or communication problems Issues related to Exceptions: Presence or absence of predefined exceptions Scope of user-defined exceptions Passing of control to the handler: Termination or resumption model 18 OOP

  19. Object and Class representations In Software engineering, class diagram and object diagram are used to represent the information about classes and objects Class diagram is used to provide information about the class; object diagram is used to indicate information about objects This representation is done in Unified Modeling Language (UML) Class/Objects representation: Represented as box with three rows class name, attributes (member variables) and the operations (member functions) associated with the class Visibility of the class Public is represented as +, Protected as #, Private as -,Package as ~ 19 OOP

  20. Object and Class representations Association in class diagram Association indicates “owns a” relationship. Company offers trainings. Company and Training are classes. One company (1) can conduct many (1..*) trainings Aggregation and Composition Aggregation indicates “has a” relationship If container (Toyoto) is destroyed, the contents (Car) are not destroyed Composition indicates “owns a” relationship if the container (Circle) is destroyed, the contents (Point) are also destroyed 20 OOP

  21. Object and Class representations Generalization Indicates “is a” relationship subclass implementing Base class Inheriting an implementation 21 OOP

  22. Object and Class representations Dependency Indicates a weak relationship between two or more classes In this example, any change in Package 2 will affect Package 1. Object data representation Class instance record (CIR) is used along with virtual method table (or virtual function table or dispatch table or vtable) to represent a class in the memory CIR contains the necessary member variables and a pointer to the vtable (called as vpointer or virtual table pointer) that contains the member functions that ought to be dynamically bound 22 OOP

  23. Object and Class representations (C++) class A { public: void fn1() { } virtual void fn2() {} int avar; }; class B : public A { public: void fn2() {} int bvar; }; int main() { B *b1 = new B(); } vtable contains only the member variables and pointers to other vtables. The non-virtual functions are not stored in the vtable 23 OOP

  24. Object and Class representations (Java) class A { public int avar; public void fn1() { } public void fn2() { } }; class B extends A { public void fn2() {} public int bvar; }; public Sample { public static void main(String[] args) { B b1 = new B(); } } In Java, all methods are dynamically bounded and thus all methods exist in the vtable 24 OOP

  25. Design Issues in OOP Pure object-oriented language: Everything should be considered as an object (including primitive data types like integer) Everything as object slows the operation on simple objects. Use imperative typing system and add objects to it Include imperative style typing system for primitive data types with everything else as objects Subclasses as subtypes “is-a” relationship holds between a parent class object and an object of the subclass Sometimes, subclass might add new methods or methods with different signature If there exists a "is-a" relationship between the parent and the subclass, then the subclass is called as subtype 25 OOP

  26. Design Issues in OOP Allocation and de-allocation of objects Can be done on heap or run-time stack Object allocation on stack Limitation on the expandability of the element With p1 as variable for parent class and c1 as variable for subclass, if space is allocated for p1 and we assign p1 = c1, problem persists if c1 has more elements than p1 Object allocation on heap How about de-allocation: Implicit or explicit? If only the interface of the parent class is visible to the subclass, it is called as interface inheritance If the subclass inherits the exact behaviour of the parent by default, it is called as implementation inheritance. Dynamic (Late Binding) and Static binding: Dynamic binding should be handled at run time Using dynamic binding always makes the process slower and thus inefficient 26 OOP

  27. Copying of Assignment Values In assignment: Right hand side expression is evaluated and the result is copied to the left hand side Two ways to do assignment: Copy semantics (also called as value semantics) means the value of the particular element is copied and not the pointer. Reference semantics (also called as pointer-copy semantics) means that the pointer is copied and not the values Java like Smalltalk uses reference semantics for arrays and objects. But for primitive data types, Java uses copy semantics. C and C++ languages support reference semantics for arrays. C++ supports both copy and reference semantics for objects #include <stdio.h> int main() { int array1[3] = {1,2,3}; int array2[3] = {2,3,4}; array1 = array2; // compilation error. return 0; } 27 OOP

  28. Copying of Assignment Values #include <iostream> using namespace std; class A { public: int i; A() { i=0; } A(int j) { i=j; } }; int main() { A *rs1 = new A(10); A *rs2; // reference semantics rs2=rs1; // print RS1, RS2 addresses and values delete rs2; A cs1(10); A cs2; //copy semantics cs2 = cs1; // print RS1, RS2 addresses and values return 0; } 28 Output: // reference semantics Address of RS1:0x10a2dc8 Address of RS2:0x10a2dc8 Value at RS1:10 Value at RS2:10 // Both RS1 and RS2 remains the same address. // copy semantics Address of CS1:0x22cc98 Address of CS2:0x22cc94 Value in CS1:10 Value in CS2:10 OOP

  29. Copy semantics in Java (using clone()) class Example { public static void main(String[] args) { int[] x = {1,2,3}; int[] y = x; x[0] = 40; System.out.println("y[0] = " + y[0]); // Prints 40 System.out.println("x[1] = " + x[1]); // Prints 2 System.out.println("y[1] = " + y[1]); // Prints 2 int[] y1 = (int[])x. clone(); System.out.println("y1[0] = " + y1[0]); // Prints 40 System.out.println("x[0] = " + x[0]); // Prints 40 y1[1] = 10; // this change impacts only y1 and not x or y System.out.println("y[1]= " + y[1]); // Prints 2 System.out.println("x[1]= " + x[1]); // Prints 2 System.out.println("y1[1] = " + y1[1]); // Prints 10 } } 29 OOP

  30. C++ and its support for OOP Main function returns an integer but we indicate the return type as void to indicate no return value Destructor procedure (represented by the same class name preceded by a tilde) is called automatically just before the object disappears C++ uses mixed type system because it includes the type system of C and adds classes to it C++ supports both object oriented and imperative type of coding and thus uses static binding by default To use dynamic binding, keyword virtual has to be used Objects are created on stack as well as on heap new operator: Used to dynamically allocate an object Used to take the input parameters and passes them into the object constructor, and returns a pointer to the memory location of the created object 30 OOP

  31. C++ and its support for OOP Creating objects on the stack: classname classname(arguments); Creating objects on the heap: classname* objectname = new classname(arguments); delete objectname; // delete the object If an object of a subclass that has extra attributes is copied onto an object of the super class, then only those attributes defined in super class are copied. This process of not copying everything is called as slicing. Accessing Members of a class: Statically allocated object: dot operator “.” Dynamically allocated object: arrow operator “->” 31 OOP

  32. C++ and its support for OOP Inheritance Access Controls: private or public or protected Private members are visible only to the class and the friends. Public members are visible in subclasses and clients. Protected members are visible in the class and in the subclasses but not in the clients Subclasssing uses access controls like private or public Private derivation means inherited public and protected members are private in the subclasses. Public derivation means public and protected members are also public and protected in subclasses Default is private for classes and public for struct 32 OOP

  33. C++ and its support for OOP Subtyping Called as interface inheritance If X inherits from Y, then C++ type checker will allow X objects to be assigned to Y class pointers Multiple Inheritance Name conflicts are resolved using scope resolution operator Name clash is possible if classes A and B have the same name and Class C inherits from these two classes Implicit resolution: The language resolves the existing name conflict with an arbitrary rule. Explicit resolution: The programmer must explicitly specify how to resolve the name conflict in his code. Disallow name clashes: Name clashes are not allowed in programs 33 OOP

  34. C++ and its support for OOP Dynamic Binding Using keyword virtual, dynamic binding is implied. This is because compiler cannot always determine which version of the function is being called To declare a function virtual, precede its prototype with the keyword virtual. Any class with an abstract method is called as an abstract class, but those which have only pure virtual methods and no data are called as pure abstract class. A pure virtual function is one without any definition. A class that has at least one pure virtual function is an abstract class class abc { public: virtual double xyz () = 0; // pure virtual … }; 34 OOP

  35. C++ and its support for OOP Friend classes and functions Friend mechanism allows the programmer to bypass class restrictions class A1 { friend class A2; }; Class A1 declares class A2 as its friend. By doing this, member functions of class A2 are permitted to directly read or modify the private data entities of class A1 #include <iostream> using namespace std; class mainclass { int private_data; friend class friendclass; public: // does not matter if it is private also mainclass() { private_data = 10; } }; class friendclass { public: int addition(int a) { mainclass mainclassobj; // access private variable of the mainclass return mainclassobj.private_data + a; } }; int main() { friendclass friendclassobj; cout << "Result: "<< friendclassobj.addition(5)<< endl; } 35 OOP

  36. C++ and its support for OOP Encapsulation Using C++ Namespaces #include <iostream> using namespace std; namespace one { int a = 10;} namespace two { double a = 10.1234;} int main () { using namespace one; cout << a << endl; // access a in one cout << two::a << endl; // access a in two using one::a; cout << a << endl; // access a in one // scope for using a namespace with brackets { using namespace one; cout << a << endl; } { using namespace two; cout << a << endl; } return 0; } 36 OOP

  37. C++ and its support for OOP Templates Used to provide overloaded functions #include <iostream> // iostream.h is depreciated using namespace std; // needed for cout to work template <typename T> T min1(T x, T y) // min is an inbuilt name and thus use min1 { return x < y ? x : y; } int main() { // Here the min1 function is being called with different data types int i = 1 ,j = 2; cout << min1(i,j) << endl; float a = 2.0, b = 3.0; cout << min1(a,b) << endl; string s = "abc", t = "def"; cout << min1(s,t) << endl; return 0; } 37 OOP

  38. C++ and its support for OOP Exceptions Does not have predefined exception types Standard library modules provide exceptions and exception mechanisms. #include <iostream> #include <vector> #include <exception> #include <stdexcept> // out_of_range exception using namespace std; int main( ) { char array[] = {'a', 'b', 'c', 'd'}; // no error is caught and just a random value is printed. try { cout << array[10000]; } catch(std::out_of_range& e) {cerr << e.what( ) << '\n';} vector<char> v; v.push_back('a'); v.push_back('b'); v.push_back('c'); // Runtime error: vector :: _M_range_check occurs try { cout << v.at(10000) << '\n'; } catch(std::out_of_range& e) { cerr << e.what( ) << '\n';} } 38 OOP

  39. Java and its support for OOP All data are objects except the primitive types All primitive types have wrapper classes that store one data value (wrapper Integer for the primitive type int). Wrapper classes are used to wrap primitive values and make them as objects As all methods in wrapper class are static, we could use them without creating an instance import java.util.*; public class Wrapper{ public static void main(String argv[]){ Vector v = new Vector(); // add needs the parameter to be an object // wrapper class converts the integer into an object v.add(new Integer(100)); v.add(new Integer(200)); for(int i = 0; i < v.size(); i++){ Integer ival =(Integer) v.get(i); System.out.println(ival); } } 39 OOP

  40. Java and its support for OOP All objects are allocated as heap-dynamic and referenced through reference variables Garbage collector runs as a thread (low priority process) Explicit calling of garbage collector in Java could be done using System.gc() Invoking or automatic running of garbage collector calls a special method called finalize in Java, which acts like a destructor Keyword super: Used to invoke the overridden method class A { void fn(){ System.out.println("a.fn"); } } class B extends A { void fn(){ System.out.println("b.fn"); super.fn();} } public class Binding { public static void main(String[] args) { B a = new B(); a.fn(); // prints b.fn and a.fn } } 40 OOP

  41. Java and its support for OOP Access Modifiers Static [shared by all instances of the class], Public, Protected and Private Substring Method Its of the form string_name.substring(begin,end) Returns all the characters from the location "begin" till the location just before the "end" argument, i.e., it does not include the "end" argument Static Field A field declared as static is one per whole class static { … } // This is called as static initialization block public class StaticTest { static int foo = 123; static { foo = 99; System.out.println(foo);} public static void main(String argv[]){ System.out.println(foo); } } This program prints 99 twice. 41 OOP

  42. Java and its support for OOP Inheritance Uses extends keyword Only single inheritance is allowed Multiple inheritance can be done only with interfaces (abstract methods) All of the methods in an interface must be abstract; only constant (final variables) may be concretely declared in an interface Interface will not have a constructor When an interface is extended, then all methods present in the interface should be implemented class A { final void fn(){ System.out.println("a.fn"); } } class B extends A { // Compilation error – B cannot override fn() in A void fn(){ System.out.println("b.fn"); } } final class C { } // Compilation error – cannot inherit from final C class D extends C { } 42 OOP

  43. Java and its support for OOP The final modifier Class indicated as final cannot be extended and thus cannot be a parent class The abstract modifier An abstract class is declared with the keyword abstract and may or may not contain abstract methods If a class contains an abstract method, then the class must be declared as abstract class The difference between interfaces and abstract classes is that abstract class can contain fields that are not static and final and also can contain implementation methods Dynamic Binding All messages are dynamically bound to methods, unless the method is final (means it cannot be overridden; therefore, dynamic binding serves no purpose) If a method is specified as private or static, then it will disallow overriding and thus will be statically bound 43 OOP

  44. Java and its support for OOP 44 OOP

  45. Java and its support for OOP Overloading Can have different signatures for a single method Handled at compile time by matching the arguments if the method that is invoked is an instance method, then checking can be done only at runtime, using dynamic method lookup Encapsulation Provided using classes and packages Package can contain more than one class definition Package scope makes the entities visible throughout the package it is defined. But, not visible to subclass in other packages Every class in a package is a friend to the package scope entities elsewhere in the package. So, it is like friends in C++ package packagename; import packagename.classname; import directoryname.subdirectoryname.packagename.classname; 45 OOP

  46. Java and its support for OOP In java.lang.String.substring(), java.lang stands for the packagename and String stands for the classname and substring() stands for the methodname Major difference between Java and C++ is that in Java all method dispatching is done at run time, usually referred to as virtual methods. Vector v; … System.out.print(v.toString()); Run-time type of v is unknown; it could be a Vector, a Stack, or some other subclass of Vector. So the actual toString method invoked depends on run-time type of v Exceptions: try .. catch .. finally class Exceptions { public static void main(String[] args) { System.out.println("Array Bound Test"); // Assign array of 10 elements. int [] array = new int[10] ; try { array[20] = 1; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Out of Array Bounds error."); } } } 46 OOP

  47. C# and its support for OOP C# is based on C++ and Java Access modifiers: internal, protected internal Types or methods indicated as internal are accessible to any files within the same assembly. The modifier protected internal, includes the features of both protected and internal. Class instances are heap dynamic Default constructor is implicitly added, if there is no explicit constructor Structs are lightweight classes which has no inheritance support To access data members, accessor methods (getter and setter) are used Files can be grouped using C# Assembly Inheritance in C# is similar to that of Java, except that the syntax is similar to that of C++ public class Weather : forecast { … } 47 OOP

  48. C# and its support for OOP public class AcademicYear { public int Days { // Days is a property get { return days; } set { days = value; } } private int days; } AcademicYear ay = new AcademicYear(); int holidays, holidaysnow; ay.Days = holidays; holidaysnow = ay.Days; Dynamic binding requires virtual and override keywords public class forecast { public virtual readvalue () { … } } public class Weather : forecast { public override readvalue () { … } } 48 OOP

  49. C# and its support for OOP Access Modifiers By default, class methods and fields are considered private Namespaces in C# are always public Classes and interfaces defined are either public or internal Classes are by default considered to be internal There is no access modifier for enumerations, they are by default public. Exceptions Similar to Java and C++ Using of catch is optional and thus finally can be used alone User-defined exceptions can also be specified An exception can be thrown so as to be caught from another class 49 OOP

  50. C# and its support for OOP public static void Main() { int x = 0; int division = 0; try { division = 100/x; } // can be used to catch all exceptions catch { Console.WriteLine("Exception"); } finally { // Prints the finally block Console.WriteLine("Finally Block"); } } 50 OOP

More Related