Object Oriented Technology Object-oriented technology is built upon a sound engineering foundation, whose elements we collectively call the object model. The object model encompasses the principles of abstraction, encapsulation, modularity, hierarchy, typing, concurrency, and persistence. 1
Object-oriented programming We present a rich style in program structure based on a collection of stateful entities (abstract data types) Most popular current representatives are C++, and Java An object-oriented design model Principle programming techniques Relation to other models (higher order programming, component based programming, functional) Case-study in object-oriented language (based on Mozart/Oz) 2
Objects Objects are the basic run-time entities in an object-oriented system. Programming problem is analyzed in terms of objects and nature of communication between them. When a program is executed, objects interact with each other by sending messages. Different objects can also interact with each other without knowing the details of their data or code.
Classes A class is a collection of similar objects. It is a template where certain basic characteristics of a set of objects are defined. The class defines the basic attributes and the operations of the objects of that type. Defining a class does not define any object, but it only creates a template. For objects to be actually created instances of the class are created as per the requirement of the case. Once a class is defined, any number of objects can be created which belong to that class
Data Abstraction Data Abstraction refers to the act of representing essential features without including the background details or explanations. In other words, Abstraction consists of focusing on the essential, inherent aspects of the entity and ignoring it Classes use the concept of abstraction and are defined as a list of abstract attributes. The abstraction of an object varies according to its application. For instance, while defining a pen class for a stationery shop, the attributes of concern might be the pen color, ink color, pen type etc., whereas a pen class for a manufacturing firm would be containing the other dimensions of the pen like its diameter, its shape and size etc.
Encapsulation Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. In other words, Encapsulation is the term given to the process of hiding all the details of an object that do not contribute to its essential characteristics. So, encapsulation hides the implementation details of the object and the only thing that remains externally visible is the interface of the object. (i.e.: the set of all messages the object can respond to)
Modularity Modularity is designing a system that is divided into a set of functional units (named modules) that can be composed into a larger application. A module represents a set of related concerns. It can include components, such as views or business logic, and pieces of infrastructure, such as services for logging or authenticating users. Modules are independent of one another but can communicate with each other in a loosely coupled fashion. In other words, the act of partitioning a program into individual components can reduce its complexity to some degree is known as modularity. So, modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.
Benefits / Advantages of OOM: The following benefits can be achieved by adopting OOM: Represents the problem domain: Object Oriented Methodology closely represents the problem domain. Because of this, it is easier to produce and understand designs. More Flexible: The objects in the system are immune to requirement changes. Therefore, allows changes more easily. Facilitate reuse: Object Oriented Methodology designs encourage more re-use. New applications can use the existing modules, thereby reduces the development cost and cycle time. More Natural: Object Oriented Methodology approach is more natural. It provides nice structures for thinking and abstracting and leads to modular design. Improve productivity: Application development is facilitated by the reuse of existing components which can greatly improve the productivity and facilitate rapid delivery. Deliver high quality system: The quality of the system can be improved as the system is built up in a component manner with the use of existing components which are well-tested and well-proven. Lower maintenance cost: The associated property of traceability of OOM can help to ensure the impact of change is localized and the problem area can be easily traced. As a result, the maintenance cost can be reduced. Manage complexity: The use of OOM eases the process in managing complexity. By the breaking down of a complex solution into different components and with each component encapsulated (e.g. treated as a black box) from others, complex development can be better managed
Disadvantages of OOM: The following are the disadvantages of OOM: Object-oriented methodology is not Exact Solution Object-oriented methodology is not a puretechnology Object-oriented methodology is not yet completely accepted by major vendors Cannot find qualified programmers and DBA s
Inheritance Programs can be built in hierarchical structure from data abstractions that depend on other data abstractions (Components) The object style of data abstraction is the default, not the ADT style Object-oriented programming (inheritance) is based on the idea that data abstractions have much in common Example, sequences (stacks, lists, queues) Object oriented programming builds data abstractions incrementally, this is done by inheritance A data abstraction can be defined to inherit from another abstract datatype, have substantially the same functionality of the other abstract datatype Only the difference between a data abstraction and its ancestor has to be specified 10
Instances (objects) Interface (what methods are available) State (attributes) procedures (methods) 11
Classes as complete spec of a data abstraction We start our case study elements of a class (members) attributes (multable instance variables) features (stateless info about objects) methods 12
Classes as incremental specs of data abstractions Object-oriented programming allows allows us to define a class by extending existing classes Three things have to be introduced How to express inheritance, and what does it mean? How to access particular methods in the new class and in preexisting classes Visibility what part of the program can see the attributes and methods of a class The notion of delegation as a substitute for inheritance 13
Inheritance Inheritance should be seen as a way to specialize a class while retaining the relationship between methods In this way it is a just an extension of a data abstraction The other view is inheritance is just a (lazy) way to construct new general class specialized class 14
Static and dynamic binding Dynamic binding Inside an object O we want to invoke a method M This is written as {self M}, and chooses the method visible in Othe current object an (M instance of D) of D class C meth M class D a subclass of C meth M 15
Static and dynamic binding Static binding Inside an object O we want to invoke a method M in a specific (super) class This is written as C, M and chooses the O method visible an instance the super class C (M of Dof C) class C meth M class D a subclass of C meth M 16
Static method calls Given a class and a method head m( ), a static method-call has the following form: C, m( ) Invokes the method defined in the class argument. A static method call can only be used inside class definitions. The method call takes the current object denoted by self as implicit argument. The method m could be defined in the class C, or inherited from a super class. 17
Inheritance class Account attr balance:0 meth transfer(amount) balance := @balance+amount end meth getbal(b) B = @balance end end A={New Account transfer(100)} 18
SuperClass relation SuperClass relation is directed and acyclic. C 19
Multiple inheritance example class Account attr balance:0 meth transfer(amount) balance := @balance+amount end meth getbal(?b) B = @balance end end class Customer attr name meth init(n) name := N end end class CustomerAccount from Customer Account end A={New CustomerAccount init} 20
Controlling visibility Visibility is the control given to the user to limit access to members of a class (attributes and methods) Each member (attribute or method) is defined with a scope (part of program text that the member can be accessed by name) Programming languages use words like public, private, and protected to define visibility Unfortunately, different languages use these keywords to define different scopes Source of enormous confusion! Be careful! 21
Public and private scopes In Smalltalk and Oz, a private member is one which is only visible in the object instance The object instance can see all the private members in its class and its super classes In C++ and Java, a private member is visible among all instances of a given class, but not to subclasses A public member is visible anywhere in the program By default, attributes are private and methods are public 22
Public and private scopes Other scopes can be programmed by using name values (as we saw for secure ADTs) For example, let us make a method private within a class (like C++ and Java) The method name is a name value Define a new name A Use the syntax!a for the method name Short-cut: Use the syntax A for the method name makes the NewName implicit With names, any kind of privacy can be programmed local A={NewName} in class C meth!a(...)... end... end end class C meth A(...)... end... end 23
Summary of scopes In Java, in order from least to most visible: Private: accessible within a class (among all its objects) Package: accessible within a package Protected: accessible within a package and to subclasses Public: accessible to all In Oz, in order from least to most visible: Private: accessible within one object (not possible in Java!) Programmed (with name value): any accessibility 24
Programming techniques Constructing a hierarchy by following the type Abstract and concrete classes First class messages Parameterized classes Use of multiple inheritance 25
Abstract and concrete classes ListClass NilClass ConsClass ListClass is an abstract class, i.e., a class in which some methods are left undefined (such as init and append) Abstract classes are not intended to be instantiated, but inherited from Inheritance fills in the blanks by adding the missing methods The result is a concrete class, i.e., a class that can be instantiated since all its methods are defined NilClass and ConsClass are concrete classes This technique is an example of higher-order programming (namely genericity: passing a procedure value, i.e., a method) 26
Class Members A class can have three kinds of members: fields: data variables which determine the status of the class or an object methods: executable code of the class built from statements. It allows us to manipulate/change the status of an object or access the value of the data member nested classes and nested interfaces 27
More about field modifiers (1) Access control modifiers private: private members are accessible only in the class itself package: package members are accessible in classes in the same package and the class itself protected: protected members are accessible in classes in the same package, in subclasses of the class, and in the class itself public: public members are accessible anywhere the class is accessible 28
Methods Declaration Method declaration: two parts 1. method header consists of modifiers (optional), return type, method name, parameter list and a throws clause (optional) types of modifiers access control modifiers abstract the method body is empty. E.g. abstract void samplemethod( ); static represent the whole class, no a specific object can only access static fields and other static methods of the same class final cannot be overridden in subclasses 2. method body 29
Methods Invocation Method invocations invoked as operations on objects/classes using the dot (. ) operator reference.method(arguments) static method: Outside of the class: reference can either be the class name or an object reference belonging to the class Inside the class: reference can be ommitted non-static method: reference must be an object reference 30
Method - Overloading A class can have more than one method with the same name as long as they have different parameter list. public class Pencil {... public void setprice (float newprice) { price = newprice; } } public void setprice (Pencil p) { price = p.getprice(); } How does the compiler know which method you re invoking? compares the number and type of the parameters and uses the matched one 31
Methods Parameter Values Parameters are always passed by value. public void method1 (int a) { a = 6; } public void method2 ( ) { int b = 3; method1(b); // now b =? // b = 3 } When the parameter is an object reference, it is the object reference, not the object itself, getting passed. Haven t you said it s past by value, not reference? 32
The Main Method - Concept main method the system locates and runs the main method for a class when you run a program other methods get execution when called by the main method explicitly or implicitly must be public, static and void 33
Class Template: Pattern or design that describes a set of elements that are distinctly related to one another and that are organized in a consistent structure and that together describe a real world or technological abstract entity. Members Data Method Object An exemplar of a class realizing the pattern or class. The template come to life. An Object is said to be an Instance of a class. To create an Object is to Instantiate and Class. Constructor Method that provides instructions for instantiating a class. 34
For example: Class: Dog Class: Collie Class: Terrier Class: Chihuahua Class: Car Class: Ford Class: GM Class: Chrysler Class: Car Class: Mini Van Class: Sports Car Class: SUV 35
O O Speak Inheritance In an Object Oriented system, a programmer can create a class that is a more specialized version of an existing class. This new class would Inherit the attributes and behaviors of the existing class. In design terminology the new class is referred to as a subclass or child class. The original class will be referred to as a superclass, a parent class, or an ancestor class. In implementation, each is just a class. Some systems support Multiple Inheritance where a class can inherit from more than one, independent classes. Other systems find ways around it. 36
For example: Class Car Public Color Car.color = Blue Class Horse Private Color Public SetColor(colorVal) Horse.SetColor( Brown ) Class Dog Protected Color Class Collie (Extends Dog) Public SetColor(colorVal){ Color = colorval} Collie.SetColor( Gold ) 37
Polymorphism This feature of O O languages allows the programmer to apply a common method among different classes. Method execution can vary by arguments passed. Helps keep thinking and programming synchronized. Overloading 38
Polymorphism This feature of O O languages allows the programmer to apply a common method among different classes. Method execution can vary by arguments passed. Helps keep thinking and programming synchronized. Overloading Fido.speak() = Bark() Greg.speak() = Oration() 39
Operators (+,-,*,etc.) can be overloaded as well. Consider: 1+2=3 Class Invoice Account ID (Character) Date (Date) Type (Character) Amount (Number) vs InvoiceA + InvoiceB =? 40
Primitives The data types that comprise the basic building blocks of an O O language. Rejected by purists (O O Snobs). Provide the tools needed to create classes. Primitives in Action Script 3: int 32-bit signed whole number uint 32-bit unsigned whole number Number Floating point number (allows decimal value) Boolean True/False String Series of 16-bit characters Null Expresses nothingness for all data types Void Like Null, applies only to functions/methods. 41
Event Not truly an O O term Originally described something happening in the user interface Can be simulated; can be totally artificial Gives user more control over process flow Easily implemented on O O platform 42
1. What is Data Abstraction? Abstract Data Types (ADTs) type implementation & operations hidden implementation types are central to problem solving a weapon against complexity built-in and user-defined types are ADTs 43
5. Classes as User-Defined Types Once the class has been defined, it can be used as a type in declarations as follows: Time sunset, //object of type Time arrayoftimes[5], //array of Time objects *pointertotime, //pointer to a Time object 44
Procedural vs. Object-Oriented Procedural Object Oriented Withdraw, deposit, transfer Customer, money, account 45
Mapping the world to software Objects in the problem domain are mapped to objects in software 46
Instantiation An Object is instantiated from a Class BankAccount myaccount; myaccount = new BankAccount; 47
Abstraction Management of complexity Hierarchical classification: is-a relationship: inheritance has-a relationship: containment 48
Polymorphism One interface Multiple implementations Inheritance Method overloading 49
What is a good class? A class abstracts objects A class should be non-trivial in the context of the program (has data structures and operations different from other classes) 50
Constructors One of the best innovations of C++ special method (s) invoked automatically when an object of the class is declared point (int x1, int x2); point (); point (double alpha; double r); point p1 (10,10), p2; p3 (pi / 4, 2.5); Name of method is name of class Declaration has no return type. 51