Object Oriented Programming

advertisement
The principle of least astonishment:
Don’t surprise the user.
Make simple things easy.
Make difficult things possible.
Programming a computer is, and will always be, one of the most difficult tasks ever undertaken by
humans
What is Object Oriented Programming?
What is OOP?
Answer:
ENCAPSULATION
INHERITANCE
POLYMORPHISM
Object Oriented Programming is not simply a few new features added to programming languages. Rather
it is a new way of thinking about the process of decomposing problems and developing solutions.
Encapsulation
An object is an encapsulation of state (data values) and behavior (operations) , that is an ADT.
Objects can be envisioned as autonomous agents that know things (data) and know how to do things
(operations).
We use the term encapsulation to mean that there is a strict division between the inner and outer view
An important benefit of encapsulation is that it permits us to consider the possibility of interchangeability
of parts.
Inheritance
The OOP concept of inheritance is borrowed from biology. We classify living things using taxonomy.
Kingdom
Animalia
Phylum
Mollusca
Chordata
Class
Gastropoda
Reptilla
Mammalia
Order
Mesogastrapoda
Predentata
Primates
Family
Cypraeidae
Ceratopsidae
Hominidae
Genus
Cypraea
Triceratops
Homo
species
Tigris
Horridus
Sapiens
Classes can be organized into a hierarchical inheritance structure. A subclass will inherit attributes from
its parent class higher in the tree. An abstract parent class is a class for which there are no direct instances;
it is used only to create subclasses.
Polymorphism
The most common form of polymorphism is when we want to treat derived types as if they are base types.
This allows us to interchange objects or add new objects to the system without affecting the system.
The message will be the same but the action will be specific to the receiving object.




Function overloading
Method overriding by subclass
Polymorphic variable
Template
533555271
What is an objected oriented program?
An object-oriented program is structured as a community of interacting agents called objects. Each object
has a role to play. Each object provides a service or performs an action that is used by other members of
the community to solve the problem. Objects communicate by sending and receiving messages.
Messages
Action is initiated in an object-oriented program by the sending of a message to an object responsible for
the action. The message encodes the request for an action and is contains by any additional information
(arguments) needed to carry out the request. The receiver is the object to which the message is sent. If the
receiver accepts the message then it accepts the responsibility to carry out the indicated action.
A message is different from a call.
1. A message is directed at a designated receiver. In a call there is no designated receiver.
2. The interpretation of the message (that is, the method used to respond to message) is determined
by the receiver. The response may vary with different receivers.
3 A function call is bound to the code at compile time (static/early binding). A message may use
static binding or may use run time binding (late binding).
Responsibilities
A fundamental concept in object-oriented programming is to describe behavior in terms of responsibilities
By discussing a problem in terms of responsibilities we increase the level of abstraction. This permits
greater independence between objects, a critical factor in solving complex problems.
Why use OOP?
Faster and cheaper development
Cheaper maintenance
Easier design and analysis
Increased productivity
Flexible
Abstraction:
Each object is normally small and self contained
OOP(ADT) allows you to describe the problem in the vocabulary of
the problem, rather in terms of the solution (underlying machine). We
do this by creating ADT’s
reuse of objects inheritance and aggregation
To change the system just change some object types or
add new types no ripple effect
We use abstraction to manage complexity.
OOP uses abstractions to model real world things.
To build an abstract data type, we must be able to do the following:
1.
Export the type definition
2
Make available a set of operations that can be used to manipulate instances of the type.
3
Protect the data associated with the type so that they can be operated on only by the provided
routines
4
Make multiple instances of the type.
533555271
Levels of
Abstraction
Highest level View
Client side View
Service side View
Module View
Lowest level View
Problem Domain
In designing a object oriented program there are many levels of abstraction
to consider
At the highest level a program is viewed as a “community” of objects that must
interact with each other in order to achieve their common goal. Each object in
this community provides a service that is used by others members of the
organization. At this highest level of abstraction, the important features to
emphasize are the lines of communication and cooperation and the way in
which the members must interact with each other.
The client sees a service object as an interface, a mechanism that describes the
service object’s behavior
The service must chose how it will implement the abstract behavior of the
interface
Groups of objects working together as a unit. i.e. Java package, C++ namespace
The last level of abstraction is the single task in isolation that is the actual
implementation of a single method.
An abstraction of the problem to be solved
Solution Domain
An abstraction of the machine to solve the problem (i.e. the program)
It is the task of the programmer to map the Problem Domain to the Solution Domain
At each level, certain information has been included and certain information has been excluded.
Information hiding: The purposeful omission of details in the development of an abstract representation.
Interface and implementation
Interface is the what.
Interfaces are fundamental in object-oriented systems. Objects are known only through their interfaces.
Implementation is the how
Procedural Programming:
Structured system analysis
Structured system design
Structured programming
Drawbacks:
Define some data then write functions to manipulate data
Data Flow Diagrams
decompose problem into small manageable modules
sequence – decision – loops
inflexible-ripple effect low reuse
OOP Design
The most important aspect of OOP design is the creation of a system of largely autonomous agents whose
interactions are going to solve the problem.
There are many design techniques and methodologies.
View objects as ADTs.
ADTs have two views:
Client view:
The client views the ADT as a interface . that is, a collection of methods that
defines the behavior of the ADT
533555271
Programmer view:
The programmer views the ADT as data variables which maintain the internal
state of the ADT
OOP request the data perform a service
OOP Programming:
OOP(ADT) allows you to describe the problem in the
vocabulary of the problem, rather in terms of the solution
(underlying machine). We do this by creating ADT’s
All programming languages provide an abstraction.
Assembly language is an abstraction of the machine
C language is an abstraction of assembly language
Abstract Data Type ( ADT)
A data type whose properties( domain and operations) are
specified independently of any particular implementation.
We refer to the elements in the problem domain and their
representations in the solution domain as objects
Objects
Two categories of OOP programmers:
 Class Creators: those who create new classes
 Client Programmers: programmers who use the classes in their applications
Ideally we have a few experts who design the best objects for the rest of us to use
The most desirable position for OOP programmers is to find and utilize existing objects to solve the
application problem.
 find a library (framework) of well designed easy to use objects.
 Avoid re-inventing the wheel
Toolkits and frameworks:
.NET
C++ MFC
Smalltalk
Java
VB
OWL
Objects
A computer system is a collection of interacting objects. These objects are viewed as things.
Objects know things and know how to do things
Things have attributes (knows things) and exhibit behaviors (know how to do things)
Things have a state (values). You can ask an object to change its state.
Users interact with objects by telling the object to do something and the object interacts with the user by
doing what is requested.
533555271
Other objects may also tell objects to do something
With the objected oriented approach you first need to identify all of the objects that will be needed to do
the task. This is a difficult task.
encapsulation
granularity
dependency
flexibility
performance
evolution
reusability
etc….





Everything is an object
A program is a bunch of objects interacting with each other by sending messages
Each object has its own memory made up of other objects
Objects belong to a class
Every object has a type(i.e.class)
All objects of a particular type can receive the same message
Designing reusable objects is much more difficult and challenging.
All objects are instances of a class.
The method invoked by an object in response to a message is determined by the class of the receiver.
All objects of given class use the same method in response to similar messages.
The class is the blueprint for constructing/building objects;.
Objects belong to a class
Class describes characteristics and behaviors
Interface Type
Every object has an interface. The interface is the list of services (things) that the object can do for you.
Type is the name we assign to the interface.
Object oriented analysis
Defining all of the types of objects that are part of the users work
environment
Defining all the types of objects in the computer system and how
they interact / relationships
Writing the code that define the objects
Object oriented design
Object oriented programming
Computer Objects are abstractions of real objects. The behaviors and attributes of the object are tailored
to the specific needs of the user’s context.
Developer classification of objects
User interface objects
Operation environment objects
Task related objects
Everything is an object .
533555271
Some examples of Objects in a System
Tangible
Airplane
Book Car
Document
Roles
Employee
Customer
Student
Incidents
Events
Interactions
Devices
Flight
Helpdesk call Flood
Organizational Units
Division
Locations
Store front
Spreadsheet
Teacher
Purchase order
Sensor Timer Mouse Button
Squadron
Department
Office Desktop
CODE REUSE:
Program to an interface, not to an implementation.
Favor object composition over class inheritance.
Reusing the Implementation: Aggregation and Composition
The “has a” relationship
Compose a new class from existing classes.
Flexible: Member objects are usually private thus you can change them without affecting client code.
You can also change them at run time (dynamic binding).
AGGREGATION
If class A has a pointer or reference to an object of class D then class A aggregates class D.
Aggregation is a superset of association
COMPOSITION
If Class A has a member of variable Type E then A is Composed of E.
Composition is a superset of aggregation
Reusing the Interface: Inheritance
The “is a” or “is like a” relationship
The derived class is the same type as the base class.
Derived classes can accept the same messages.
A test for inheritance is whether you can state a “is a” relationship about the classes and have it make
sense.
Two ways to differentiate the derived class from the base class:
1 “is a “ relationship
Change the behavior by overriding the methods
2 “is like a” relationship
Add more methods(services).
533555271
POLYMORPHISM
Polymorphism is general goal in object-oriented programming.
You want the bulk of your code to know as little as possible about the specific types of objects. As a
result your designs will be easier to implement, understand and change.
Polymorphism (dynamic binding) lets you substitute objects that have identical interfaces for each other at
run time. Polymorphism simplifies the definition of clients, decouples objects from each other and lets
them vary their relationships to each other at run time.
Upcasting
Static binding
Late binding
Redefinition
overriding
Taking the address of a derived object and treating it as the address of the base class
Connecting a function call to its body at compile time
Connecting a function call to its body at run time
A derived class defines a method using the same signature as the non-virtual base
class method.
A derived class defines a method using the same signature as virtual base class
method.
C++ uses inheritance and virtual methods mechanism to implement polymorphism.
The application is written to the base class interface and has no concern for what kind of object is actually
receiving the message.
Polymorphism allows you to add a new derived object to the system and not impact the client code.




Function overloading
Method overriding by subclass
Polymorphic variable
Template
533555271
CLASSES
Typical Public Members:
Class Management Functions
Constructor
performs initializing of data members at the time of object creation.
Destructor
performs clean-up before the object is destroyed.
Copy Constructor
creating an instance and initializing it by copying from another instance
Assignment Operator
Implements assignment behavior
Class implementation Functions
implement the behavior of the data type represented by the class
Class access functions
(avoid if possible)
get and return values of private data members
set the values of private member functions
Class utility/helper functions
(often declared private)
used internally within the class for miscellaneous task
Typical Private Members:
Data members
Data members should private or protected
Class utility/helper functions
(often declared private)
used internally within the class for miscellaneous task
CLASS SCOPE
Within a class’s scope all members of the class can referenced by name.
Outside of a class’s scope members must be referenced through a handle.
Handle
|-object name
|-object reference
|-object pointer
::
SCOPE RESOLUTION OPERATOR
BINARY FORM
used to access class members when outside the class’s scope
UNARY FORM
533555271
used to access global identifiers one block level up.
class class_name
{
public:
class_name();
// default constructor
~class_name();
// defualt destructor
class_name(const class_name & rhs);
// copy constructor
const class_name &operator=(const class_name & rhs); // overloaded assignment operator
...
public function members;
private:
private data members;
private utility function members;
// helper functions
protected:
protected data members;
protected utility function members; // helper functions
};
CLASS IMPLEMENTATION
type
class_name::
function_name(parameter list,
{
function body;
}
class_name.cpp file
( function definitions)
...)
CONSTRUCTORS
Function name is the same as the class name
Constructors are special member functions that initialize the data members of a class when an
object of the class is instantiated.
The class constructor is implicitly called when the object is instantiated.
Frequently are overloaded to handle different initializations
DESTRUCTORS
Function name is the same as the class name prefixed with a
Destructors perform termination housekeeping on objects
The general form for defining constructors:
ClassX::
ClassX( args )
: init_list
{
constructor body
}
533555271
~
The optional init-list specifies all the desired initializations.
An init-list is a comma delimited list of member initializers, each member initializer has the form:
member-id(one or more args)
Member initialization is performed in declaration of the class body
For initialization purposes init-list is the right choice
const and reference members of a class must use init-list initialization
533555271
Reference
Declaring a reference variable:
type& [qualifier] identifier = lvalue;

A variable declared as type& is a reference of the given type and must be initialized at declaration
time.

The initializer must be an lvalue expression (must be real memory)

A reference is an alternate name for an object, and you can use it just as you would use the object
itself.

A reference is not a real variable
There is no need to initialize a reference under the following conditions:
Declared with extern.
Declared as a function return type.
Declared as a function parameter (the caller’s arguments will be the defacto initializer).
Is the member of a class which is initialized by the constructor.
Reference arguments are in the language for four reasons:
1 You need them to define a copy constructor
2 You need them to define operator overloads.
3 You often want to pass objects by value for semantic reasons.
Pass a reference to a const object in this situation
4 When an object of some user-defined class would normally be passed by value
use a reference to a const object instead to avoid the implicit copy-constructor call.
533555271
______________UNORGANIZED NOTES ______________
Principals of OOP paradigm:
1 Encapsulation. The object contains both the data and the methods that will manipulate or change the
data.
2 Information Hiding. The object that contains the attributes defines what services are available to
client objects. Clients do not have access to nor knowledge of the data or how the services are
implemented
3 Message Passing. Objects communicate with each other only via the message passing mechanism
4 Late Binding. Support for the ability to determine the specific receiver and its corresponding method
to be executed for a message at run time,
5 Delegation. Work is passed, via message passing from one object (client) to another object (agent)
because, from the client’s perspective the agent has the services that the client needs. Work is passed
until it reaches the object that has both the data and method to perform the work.
6 Class/Instance/Object. All objects are instances of a class. Instances can be created and destroyed at
run time.
7 Generalization without Polymorphism. Classes can be organized by using a hierarchal inheritance
structure. In the structure, the subclass will inherit the attributes, the relationships, and the methods
from the classes that are higher in the tree.
7a Generalization with Polymorphism. Classes can be organized by using a hierarchal inheritance
structure. In the structure, the subclass will inherit the attributes, the relationships, and the methods
from the classes that are higher in the tree. However, a subclass may create its own method to replace
a method of any of its superclasses in providing a service that is available at the superclass level
when an instance of that subclass is the agent.
8 Relationships. Collaborations between objects to provide a service to a client are usually captured by
an association relationship, which is technically called a link.
Object-oriented programming views a program as a collection of loosely connected agents, termed objects. Each object is
responsible for specific tasks. It is by the interaction of the objects that computation proceeds. In a certain sense, therefore,
programming is nothing more or less than the simulation of a model universe.
The behavior of objects is dictated by the object’s class. Every object is an instance of some class. All instances of the same
class will behave in a similar fashion ( that is , invoke the same method) in response to a similar request.
An object will exhibit its behavior by invoking a method ( similar to executing a function) in response to a message. The
interpretation of the message ( that is, the specific method used) is decided by the receiving object and may be different from
one class of object to another.
Classes can be linked to each other by means of the notion of inheritance. Using inheritance, classes are organized into
hierarchical inheritance trees. Data and behavior associated with classes higher in the tree can also be accessed and used by
classes lower in the tree. Such classes are said to inherit their behavior from the parent classes.
Designing an object-oriented program is like organizing a community of individuals. Each member of the community is given
certain responsibilities. The achievement of the goals for the community as a whole come about through the work of each
member, and the interaction of members with each other.
By reducing the interdependency among the software components, object-oriented programming permits the development of
reusable software systems. Such components can be created and tested as independent units, in isolation from other portions of
a software application.
533555271
Reusable software components permit the programmer to deal with problems on an higher level of abstraction. We can define
and manipulate objects simply in terms of the message they understand and a description of the task they perform, ignoring
implementation details.
An object-oriented program is structured as a community of interacting agents called objects. Each object has a role to play.
Each object provides a service or performs an action that is used by other members of the community.
Action is initiated in an object-oriented programming by the transmission of a message to an agent(object) responsible for the
action. The message encodes the request for an action and is accompanied by any additional information (the arguments)
needed to carry out the request. The receiver is the object to whom the message is sent. If the receiver accepts the message, it
also accepts the responsibility to carry out the indicated action. In response to a message the receiver will perform some
method to satisfy the request.
A fundamental concept in object-oriented programming is to describe behavior in terms of responsibilities.
By discussing a problem in terms of responsibilities we increase the level of abstraction. This permits greater independence
between objects, a critical factor in solving complex problems.
We use abstraction as a tool to understand or manage complexity.
Abstraction is the purposeful suppression or hiding of detail in order to bring out more clearly other aspects, details, or
structure.
highest
A program is a community of interacting objects. Each object provides
a service.
Lines of communication and the way
objects interact with each other
ADT
1. Extend a programming language by adding programmer-defined types.
2. Make available to other code a set of programming-defined functions that are used to manipulate
the instance data of the specific programmer-defined type.
3. Protect(hide) the instance data associated with the type and limit the access to the data to only the
programmer-defined functions
4. Make (unlimited) instances of the programmer-defined types.
Relationships
Associations (peer to peer).
Hierarchical (generalizations / specializations).
Aggregations.
Link: one object knows about another object for specific services
An association describes a group of links with common structure and common semantics.
533555271
533555271
Download