Wednesday, May 2, 2012

Object Oriented Programming (OOPs)

Object Oriented Programming (OOPs). –

The basis and foremost discussing topic is - Object Oriented Programming (OOPs). Now a day this concept is getting very popular and bit confusing too.  Almost all high level and 4th generation languages support OOPs. Therefore it becomes mandatory to deal OOPs before switching onto OOPs pillars.
 Object Oriented Programming is an abstract concept or programming approach that identifies all physical entity as a basic element of the system i.e. class. In real world if we want to understand the behavior of a system then it becomes mandatory to breakdown that entity on the level of its basic unit. Once the breaking process reaches on the level of atom or basic unit level then sudden a click comes around how anyone can identify this atom or basic unit? An atom is a basic unit of all physical entity that do well individually and holds all it nature properties and behaviors. When more than an atom sits together then it produces an element and when more than one element sit together then it makes compound element … and finally it fulfill the necessity of human life and make it easy. The meaning of these sentence is if want to make a versatile system or even a system then it becomes mandatory to understand its basic element. Similar format is used by the Object Oriented Programming. Here atom is nothing actually it is a specific class that does well individually and by joining other class make a module and by joining multiple module makes a system and in similar way it can produce a large system. If look closely to above paragraph then can say Object Oriented Programming is a programming approach that implements itself in Bottom-up fashion. So to understand Object Oriented programming it is good to see the Bottom-up approach.
Bottom-up - In a bottom-up approach, the individual base elements of the system are first specified in great detail. These elements are then linked together to form larger subsystems, which then in turn are linked, sometimes in many levels, until a complete top-level system is formed. This strategy often resembles a "seed" model, whereby the beginnings are small, but eventually grow in complexity and completeness. It's worth emphasizing that bottom-up design doesn't mean just writing the same program in a different order. When work on bottom-up, it usually ends up with a different program. Instead of a single, monolithic program, it will get a larger language with more abstract operators, and a smaller program written in it.
Bottom-up approach yields programs which are smaller and more agile. A shorter program doesn't have to be divided into so many components, and fewer components means programs which are easier to read or modify. Fewer components also mean fewer connections between components, and thus less chance for errors there. This approach also promotes code re-use. When talk about to write two or more programs, many of the utilities written for the first program will also be useful in the succeeding ones. Because it causes always to be on the lookout for patterns in the code, working bottom-up helps to clarify the ideas about the design of the program.
Hence Object Oriented Programming follows the bottom-up approach so it inherits all the features from. In a single word OOPs is Object Oriented Programming approach that oriented around object and its basic element class. In essential an Object Oriented Programming is a programming if it must supports abstraction (classes and objects), inheritance and polymorphism. It may support other features, but encapsulation, inheritance and polymorphism are the bare minimum. This is the opinion of the man who invented the term. In addition, Bjarne Stroustrup (who designed and implemented the C++ programming language), provides this broad definition of the term "Object Oriented" in section 3 of his paper called Why C++ is not just an Object Oriented Programming Language:
A language or technique is object-oriented if and only if it directly supports:
1.      Abstraction - providing some form of classes and objects.
2.      Inheritance - providing the ability to build new abstractions out of existing ones.
3.      Runtime polymorphism - providing some form of runtime binding.
Later versions of various OO languages have added more features but these features are not the deciding feature which decide if a language is OO or not. It would be like saying that a car is not a car unless it has climate control and satNav. Those are optional extras, not the distinguishing features, and not using them does not make code not OO. It would also be incorrect to say that a car is a car because it has wheels. Having wheels does not make something a car - a pram has wheels, but that does not make it a car, so having wheels is not a distinguishing feature. At this point I want to say that such features like "modularity", "reusability" and "messaging" are not features which distinguish an OO language from a non-OO language, but these features make more clarity for Object Oriented Programming approach. Because java fulfills the Basic and all enhance features of OOPs so it is sound to say that java is a complete Object Oriented Programming language.
Now it is time to understand class and object and after that description will continue on Object Orient pillars.
Class – these are some definition of class –
A class can be defined as template/blue print that describes the behaviors/states that object of its type support.  
A class can have member functions, member data, member constants, and member types.
A class is the primary mechanism for representing concepts in java. A class is also called “user defined data type”.
According to sun micro system a class is the blueprint from which individual objects are created.
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
A class is a group or set (of things or entities) with common characteristics, attributes, qualities or traits and even behaviors. A class is a noun and classes don’t hold any information. A simple example of class in java –
[Accessible modifier] class Shape {
            Properties (list of instance variables)
            Behaviors (to manage above properties)
            }
Object – when a class is created actually it creates a new data type but when object is created for that data type that mean it get physical existence of that class.  An object is contiguous region of memory holding a value and state of some type. At run time, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class. Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state. An object is an instance of a class. A class holds all the properties and functions, while object uses them.
In a brief class is an abstract data type that does not exist physically while object is a real representation of a class that lives physically and present actual visibility of a class.
Now it is time to elaborate the Object Oriented Programming pillars –
According to above description the basic OOPs pillars are – 

Abstraction (providing some form of classes and objects) – the ability to represent concepts directly in a program and hide incidental details behind well defined interfaces – is the key to every flexible and comprehensible system of any significant size. In typical words – to retain only information that is relevant for a particular purpose. For example when a car user changes the gear of his/her vehicle is user really concern about the inner details of the vehicle engine? No, but what matter is that gear must get changed that’s it! This is abstraction; show only the details which matter to the user. So abstraction says expose only the details which are concern with the user (client) of object. So the client who is using the class needs not to be aware of the inner details like how class does the operations? User needs to know just few details. This certainly helps in re-usability of the code. Let try to understand this concept in java program, suppose there is a class that interact with database and implements the database Data Manipulation Language (DML) operations like – insert, update, delete etc. Now this is not required to other developer of system to know how it interact to Database and how it manages the DML operations, just extends the class and if required then add some enhancement and performs the message call. Here the systems other developer just know like the car user, only the required information like which parameter is to pass and what will be return value. To get a complete view about abstraction in java look in the following example – 


 

 

In above example there are two java classes one is a Parts (vehicle) and another is an abstract class name is Vehicle. Vehicle class a top most class for any type of vehicle, and vehicle must have compressor piston and various more parts but for example I am taking here only two parts. As we know abstract class cannot be initialized so to get these hidden implementation need a concrete class.  As in following example there is a class HondaCity that is extending Vehicle. This class will return the compressor and piston as its company uses. In similar way every type of company or its brand has its own properties and value. So in abstract class it tried to hide the unnecessary code from developer or end user. This is just an example to understand. For any more clarification please put your query.
At last, abstraction is not hiding the data, its hiding the unnecessary work from the end user.

Encapsulation (providing some form of classes and objects)
Encapsulation means shielding the Object data inside a class. Shielding means it hides the data from view outside of the object definition. It means only the object’s own methods can directly inspect or manipulate its field. In other words – encapsulation is the concept that insulates data and its operable function inside a single unit (class), by using this technique keeps data safe from outside interfaces and misuse. This is a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside of wrapper. Encapsulation protects data inconsistency and increase robustness by allowing the developer to limit the inter dependencies between software components.
If we want maintainability, flexibility and extensibility then it becomes mandatory to follow the encapsulation features. A java class can call fully encapsulated if it follow these rules –
1.      All instance variables must be private (in case of inheritance it can be protected).
2.      To play on data, there will be public access method and it forces to call these accessor methods rather than directly accessing the instance variable.
3.      For accessor method coding convention must follow the Java Bean naming convention.

The benefit (maintainability, flexibility and extensibility) of encapsulation does not come automatically, to get these features we need to design the code accordingly. This is an example of encapsulation –

 
 Abstraction Vs Encapsulation –
These two concepts are not intercepting any one at any point, I think both are complementary and encapsulation is the next step of abstraction or I can say it makes the abstraction on concrete level.  In abstraction often it is called that is hide the unnecessary implementation while encapsulation hide  the data as well as implantation (if any changes occurs in implemented section of code, then there is no any  side effect found under dependent code – SCJP Exam 310-055 by Kathy Sierra). Abstraction is a steps or process it is act of identifying the relevant qualities and behavior of an object and an object does possess it, this ensure by the encapsulation. for example a user click on menu to save a file, does the user know how it will perform – no; so this is encapsulation hiding the  data and implementation from user. Here, Abstraction provides access to a specific part of data while encapsulation hides the data. In short both concepts make OOPs stronger by complementing each other.

 



Polymorphism
Polymorphism is the ability of one type ‘A’ to appear as and be used like another type ‘B’. More precisely, it is the ability for different objects to respond to the same message in different ways. Polymorphism types –
    1.    Overloading polymorphism (dynamic binding)
    2.    Inclusion polymorphism

Inheritance
Inheritance is a feature to acquire the characteristics from its parent. The class whose members are inherited is called parent/base class and the class that inherits is called child or derived class. Inheritance is a static binding. Inheritance demonstrate IS-A relation.

Relations
1.   IS-A Relation (Inheritance)
2.   HAS-A Relations (uses)
3.   Generalization
4.   Composition
      - Association (Has –A)
        - Aggregation

8 comments:

  1. Hi Pravind,

    I am not able to view the OOPs Concept.
    I have some query in Thread, can you pls elaborate the below statements:

    Extending the Thread class is the easiest, but it's usually not a good OO practice. Why? Because subclassing should be reserved for specialized versions of more general superclasses. So the only time it really makes sense (from an OO perspective) to extend Thread is when you have a more specialized version of a Thread class.

    What does "specialized versions of more general superclasses & more specialized version of Thread" mean?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Nice one sir. Give clear idea about abstraction and encapsulation.
    Otherwise these two topics are confusing.

    ReplyDelete
  4. Hi Pravind,

    Could you pls make me understand in layman language "What does Bottom-up approach mean" and also pls clarify the sentence "Bottom-up approach yields programs which are smaller and more agile" specially more agile means?

    ReplyDelete
  5. Hi,

    To understand about bottom-up approach -
    go to this link - http://en.wikipedia.org/wiki/Top-down_and_bottom-up_design

    ReplyDelete
  6. Hi Sir,

    Thank you very much for give this explanation about Abstraction and Encapsulation ....

    ReplyDelete