UNIT-1 - WordPress.com

advertisement
1
UNIT – I
Object Oriented Thinking:
Contents:
1.1 Need for OOPS: Differences between procedure oriented programming and object oriented
programming, concepts of object oriented programming
1.2 Way of viewing world: Agents, Communities, Messages, Methods, Responsibilities, Classes
and Instances, Class Hierarchy, Method Binding, overriding & Exceptions.
1.3 Summary of Object Oriented Programming
1.4 Coping with Complexity
1.5 Abstraction Mechanisms
1.1 Need for Object Oriented Programming:
To eliminate the flaws like focusing only on functions, data moves freely and top down approach in
Procedure languages, Object oriented programming is needed. OOPS treats data as a critical element
in the program development and doesn’t allow data to move freely around the system. OOPS allows
decomposing a problem into a number of entities called objects. The OOPS characteristics are
(i)
It focuses on data rather than functions.
(ii)
It takes a program in terms of objects.
(iii) It constructs data structures ( objects) such that they characterize the objects.
(iv)
It hides accessing data of method by external methods.
(v)
It extends existing classes ( parent classes) into sub classes which supports reusability.
(vi)
It supports bottom up approach.
(vii) It supports objects communicate with each other through methods.
This is also used for differentiating procedure and object oriented programming.
1.1.1 Object Oriented Programming concepts: The following are considered as concepts
of Object oriented programming.
(i) Classes and Objects:
(ii) Data Abstraction and encapsulation:
(iii) Inheritance:
(iv) Polymorphism
(v) Message passing
(i) Classes and Objects: A class is an user defined data type that contain data and code to
manipulate that data. Once a class is defined, any numbers of objects are created for that class. So, a
class is group of objects of similar type. For example, apple, mango and orange are members of class
Fruit.
An object is run time entity in an object oriented system. Any programming problem is
analyzed in terms of objects. The program objects be chosen closely like real world objects. An
object takes up space in memory and has an address like record in pascal or structure in C.
(ii) Data Abstraction and Encapsulation: The wrapping up of data and methods is called
Encapsulation. It is the most striking feature of a class. The data of it is not accessible to the outside
world and only methods of the class can access data of it. The insulation of data from direct access is
called data hiding. Encapsulation treats objects as black boxes and each object performs specific
tasks.
Data and
methods
Information in
Information out
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
2
Abstraction refers act of representing essential details by excluding background details. Classes use
concept of abstraction and are defined as a list of abstract attributes like size, cost & weight and
methods that operate on these attributes.
(iii) Inheritance: The process by which objects of one class acquire the properties of objects of
another class. It supports hierarchical classification. For example: The bird Robin is part of class
flying bird and is part of class bird.
Bird
Attributes:
Feathers
Lay Eggs
Flying bird
NonFlying bird
Attributes:
Attributes:
Robin
Attributes:
Swallow
Attributes:
Penguin
Attributes:
Kiwi
Fig 1.1.1: Inheritance example
There are 5 types of inheritance. They are
(i)
Single Inheritance: It creates only one sub class for the parent class. It can be shown
below.
Parent class
Derived class
(ii)
Multiple Inheritance: It creates one sub class from more than one parent classes.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
3
Parent class1
Parent class2
Parent classN
Derived class
(iii)
Multilevel Inheritance: It means the process of creating another sub class from already
created sub class.
Parent class
Derived class1
Derived class2
(iv)
Hierarchical Inheritance:
It contains several sub classes for a parent class.
Parent class
Deived class1
(v)
Derived class2
Derived classN
Hybrid Inheritance: It is combination of multiple and multilevel inheritances.
Parent class
Derived class1
Derived class2
Derived class
1.4 Polymorphism: It means an operation exhibit in multiple forms. The word poly means many.
So, it means many forms. An example to this, consider + for integer operands or for real operands,
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
4
performs addition of those two numbers. When the same operator took for two strings, the operation
gives concatenation of those two strings. It is an example to polymorphism.
There are two types of polymorphism. They are (i) compile time polymorphism
(ii) Run time polymorphism
1.5 Dynamic Binding: Binding refers to linking a procedure call to code to be executed in
response to the call. Dynamic Binding means executing a procedure is not known until run time. It is
associated with polymorphism and inheritance.
1.6 Message Passing: The steps involved in communication of objects with each other is
(i)
Creating classes that define objects and their behavior.
(ii)
Creating objects from class definitions.
(iii) Establishing communication among objects.
Objects communicate with each other by sending and receiving information as people pass messages
to one other.
Message passing involves name of the object followed by method name and information to be sent.
Employee.salary(name);
where Employee is an object, salary is message and name is parameter that contains information.
1.2 Way of viewing World:
Object oriented programming has been a hot topic over a decade and java is considered as common
perceived embodiment of object oriented languages.
Object oriented programming is a new programming paradigm. A paradigm refers an example or
model. This lets you to understand how the world works. For example, Newton model of physics
paradigm tells any thing is thrown up will fall onto the ground. Similarly, paradigm in computer
science tells how the elements are used in organizing a computer program and hoe they interact with
each other.
To illustrate out ideas in object oriented programming, consider a real world situation and see how
computer models the problem. For example, i want to send flowers to my friend sally living many
miles away. Because of distance, it’s not possible to me to get flowers and carry them to my friend’s
door. This problem can be solved easily by going to Flora and tell the number and quantity of
flowers and sally’s address.
1.1.1 Agents and Communities:
This problem can be easily solved by finding
appropriate agent called Flora. Now, Flora is responsible for sending my flowers along with the
message. He is responsible for sending message which must satisfy my request. I don’t interfere
what method or algorithm or set of operations the Flora is using.
When I investigated, i came to know that behavior involved in solving the problem. They
usually follow a procedure in which Flora in my city interact with another florist in my friend city,
who had a subordinate flower arranger who collects flowers from flower whole seller who had
interactions with garden growers who gets flowers from gardeners. Then, florist in my friend city
passes it along with message to delivery person who passes them to my friend.
Without these numbers of agents, this problem couldn’t be solved easily. The principle
considered in this is agents and communities.
An object oriented programming is structured as community of interacting agents called objects.
Each object used has a role to play. Each object performs a service or action used by other member
in the community. This overall solution is shown in the following community.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
5
Gardeners
Me
Sally
Grower
Florist
Delivery Person
Flower Arranger
Wholesaler
Sally’s Florist
Fig 1.1 : Community of agents helping me
1.1.2 Messages and Methods: A chain reaction of actions is resulted in the solution when i put a
request to florist. This request led to other requests which still led to more requests until the goal is
reached. The members in the community are community making requests with one another. The next
principle considered in object oriented programming is the vehicle by which activities are initiated.
An action is initiated by transmitting a message to the agent(called florist). The message is now
encoded the request to an action and is accompanied by whatever information is necessary to carry
out the request. The receiver is the object to whom the message is sent. When the receiver accepts
the message, he is responsible for carrying out the indicated action. In response to message, the
receiver will perform some method to satisfy the request.
A message is the request sent by an agent in the community and other agent in it encodes it and
performs an action which is called method.
An important aspect in object oriented programming is information hiding in regard to message
passing. An object oriented programming develops reusable components and the important step
considered is use of reusable components is a willingness to trust software written by others.
Information hiding is also important aspect in conventional languages. What is the difference
between massage and a procedure call. In both cases, there is a set of well defined steps that will be
initiated following the request but there are two distinctions.
The first is that a message has a designated receiver. the receiver is the some object to which the
message is sent. In a procedure call, there is no designated receiver.
The second is interpretation of message is dependent on the receiver and varies with different
receivers. For example, When i given a message to my wife Elizabeth, she will understand it and
produces outcome. In this, Elizabeth uses a message satisfying my message which different from
that used by Flora. If i asks my dentist Kenneth to send flowers to my friend .He may not have a
method to solve. if he understands it, he probably issue error diagnostic.
The selection of a message to execute in response to the message may vary with different receivers.
Determination of which method to execute is known until run time is called late biding. The same is
known at compile time is called early biding.
1.1.3 Responsibilities: The fundamental concept in object oriented programming is describing
behavior in terms of responsibilities. When i put a request, desired outcome is produced. I don’t
interference what method they were used to solve it but my goal is achieved.
When problem is viewed in terms of responsibilities, level of abstraction is also increased. This
permits greater independency between objects. The entire collection of responsibilities associated
with an object is called protocol.
The difference between traditional and object oriented programming is differentiated like
traditional operates by acting on data structures where as object oriented requests data structures to
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
6
perform a service and is quoted like Not ask what you can do for your data structures but ask what
your data structures do to you.
1.1.4 Classes and Instances: I know more information regarding florists. So, i expect Flora is
instance of this category which fits general pattern. The term florist represents category of class of
all florists. These are incorporated in next principle of object oriented programming such as classes
and instances.
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 a given class use same method in response to
similar messages.
1.1.5 Class Hierarchy: When i put a request to flora that is not necessarily be florist but may
be a shop keeper. Since Florist be a special category of Shop keeper. any knowledge about shop
keeper is also applicable to florist.
This all (means knowledge about Flora) can be organized into hierarchy of categories.
Flora is instance of category Florist who is a special form of Shop keeper. The shop keeper is a
special form of human which is special form of mammal. The mammal is who nurse their young is a
special form of animal who breathe oxygen. The animal is special form of Material Object. All of
these categories surrounding Flora is shown below.
Meterial Object
Animal
Mammal
The principle that knowledge of a more general
category is also applicable to more specific category is
called Inheritance. An example is florist shown in
hierarchy will inherit attributes of the class
ShopKeeper.
Humen
Shop keeper
Florist
Flora
Fig 1.2: Categories surrounding Flora
Another technique is often used to show these relations especially when there are many individuals
with different lineages. This technique shows the listed classes in a hierarchical tree like structure in
which more abstract classes listed top of the tree, more specific classes listed descendants of them
and individuals at bottom. This can be shown in the following tree like structure called class
hierarchy.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
7
Material Objects
Animal
Plant
Mammal
Human
Dog
ShopKeeper
Flash
Flower
Artist
Florist
Potter
Flora
Elizabeth
Platypus
Dentist
Kenneth
Carnation
Phyl
Sally’s Address
Fig 1.3: class hierarchy for various material objects
In this, the information i had about Flora which is instance of Human is also applicable to Elizabeth
and also phyl.. All the information i had about Elizabeth which is instance of Mammal is also
applicable to Flash as well. The information i possess about all members of Material objects is
equally applicable to Flora and also sally’s flowers.
This tells a child class will inherit attributes from a parent class higher in the tree. An abstract
parent class is a class for which there are no direct instances but it is used to create sub classes.
1.1.6 Method binding, method overriding and Exceptions: Mammals produce live offspring and
phyl is certainly a mammal but yet there is a difference between phyl & Phyllis in which phyl lays
eggs. To accommodate this variation, find a technique to encode exceptions to a general rule. This is
called Exception. Generally, an exception is run time error or unsual condition that halts program
execution.
Method Binding: It means linking a method call to its method associated code to execute.
There are 2 types of method binding. They are:
a) Static Binding or Early binding or Compile time binding: It means linking the method call
to its associated method at compile time. An example is method overloading. It mean several
methods in same class has same name but has different argument lists and return types.
b) Dynamic Binding or Run time Binding or late binding: It means linking the method call to
its associated method at run time. An example is method overriding. It mean a method in sub class
and a method in parent class has same name and same argument lists and return type but behavior is
different.
Method Overriding:
This can be done by decreeing the information contained in sub class can override
information inherited from a parent class. This approach take the form of a method in a sub class
have the same name as a method in the parent class. In this, how to search for method in response to
a message.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
8
This search begins at class of the receiver. If no appropriate method found, the search is
conducted in the parent class of this class. Even if it don’t contain, the search continues up the parent
class chain until either method is executed or error is raised when the parent class chain is exhausted.
If methods with same name can be found higher in the class hierarchy, that method is said to
override the inherited behavior.
Example:
class parent
{
void show()
{
System.out.println(“parent class show()”);
}
}
class child extends parent
{
void show()
{
System.out.println(“child class show()”);
}
}
class demo
{
public static void main(String args[])
{
child c=new child();
c.show(); // show() in child class is executed
}
}
Output:
child class show()
Polymorphism means Elizabeth and florist uses different methods in respond to my request.
1.3 Summary of Object Oriented Programming: Alan Kay is considered father of object oriented
programming by some one given the following characteristics for oops.
(i) Every thing is an object.
(ii) Computation is performed by objects communicating with each other requesting each other to
perform actions. Objects communicate by sending and receiving messages. A message is a request
for action bundled with whatever arguments necessary to complete the task.
(iii) Each object has its own memory which even consists of other objects also.
(iv) Every object is an instance of a class. A class represents a grouping of similar objects such as
integers or lists.
(v) The class is repository for behavior associated with an object. That is all objects that are
instances of the same class can perform the same actions.
(vi) Classes are organized into singly rooted tree called inheritance hierarchy. Memory and behavior
associated with instances of a class are automatically available to any class descendant in the tree
structure.
1.4 Coping with complexity: To understand OOPS in another way is to place it in historical
context.
The complexity is low for a small project where as it is typical or high for a large project. Example is
building a bridge over a small ditch is simple where as building a flyover on a river is complex.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
9
a) Non linear behavior of Complexity:
(i) As programming projects become large, the teams of programmers are required.
(ii) The interesting phenomenon is the task takes two months for a person requires more than one
month even for two members.
Software crisis came out when people realized major problem in software development were not
algorithmetic but were caused by communication difficulties and management of complexities.
b) Cause of Complexity:
(i) Many software systems are complex because of they are not large but because of many
interconnections.
(ii) Interconnections make it difficult to understand pieces in isolation or to carry them from one
project to another.
(iii) The inability to cleanly separate out components is difficult to divide a task between several
programmers.
(iv) Complexity is managed by means of abstraction by eliminating information that a programmer
do not need to know.
If examine the history of mechanisms used to solve the problem of complexity, the role of OOP
should be appreciated.
1.5 Abstraction Mechanisms: Abstraction is a process of reducing information content of a concept
or observed phenomenon in order to obtain relevant information for particular purpose.
Abstraction mechanism is a technique used to create, understand, and managing complex problem.
The layers involved are higher level in which important features of each object is specified, next
level in which objects interact with each other and expose some and hide remaining, next level deal
with communication between client and server, and last level takes the task in isolation.
To understand a problem, separate necessary details (model) from unnecessary. The process of
modeling is called abstraction.
a) Abstraction: There are two types of abstractions. Those are
(i) has a abstraction: division into parts: Examples- A car has an engine, A bicycle has wheel.
(ii) is a abstraction: division into specialization. Examples: A car or bicycled is a wheeled
vehicle.
b) Model: It is an abstraction used in the creation of predictive formula or solution.
A model defines abstract view to the problem and focuses only on problem stuff . It defines
(i) data which are affected
(ii) Operations which are identified
An ADT is a kind of model.
c) ADT: These are partial solutions to problems.
It defines interface to data abstraction without specifying implementation details.
Properties: (i) With abstraction, a well defined entity is created which can be properly handled.
(ii) These entities define the data structure of a set of items. For example: An employee has a
name, date of birth, social number etc.
(iii) The data structure can only be accessed with defined operations. It has a set of operations
and are exported by entity.
(iv) An entity with specific properties defined is called ADT.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
10
Abstract data structure
Operations
interface
Fig 1.5.1: ADT
The properties of ADT are: (i) it exports a type. (ii) it comprises a set of operations called
interface. (iii) Operations of the interface are only access mechanism for the type’s data structure.
(iv) Preconditions and axioms define the application domain of the type.
An example to ADT is ListADT. It has the following:
(i) It has type List
(ii) It have instances of List and operations such as search, get, insert, delete, append etc.
(iii) The axioms and preconditions include statements as a) An empty List is a List b) Let
L={d1,d2,---,dn} be a list. Then, append(dm) results a list like {d1,d2,---,dn, dm}.
(iv) The first is deleted only if list is nonempty.
d) Encapsulation: It combines both data (variables) and operations(methods) together. Its
advantages are:
(i) It allows modularity.
(ii) It has controlled access to data.
(iii) It separates implementation from interface.
(iv) It extends built in types.
S.HRUSHIKESAVA RAJU, Sr.Assistant Professor, CSE Dept, NEC, Nellore.
Download