Thursday, 15 August 2013

OOPs Objects,Classes,Abstraction and Encapsulation,Inheritance,Polymorphism


 

                            OOPS
OOP has been developed, based on issues faced in design Phases of several fields .for IT it is to remove the problems associated with earlier programming style i.e. procedural programming where everything was identified as task and converted to a procedure where as In object oriented approach we came out with everything into classes and objects based on which Simula was the first object-oriented programming language developed. With the help of this approach we get rid of lots of issues like Security, Maintainability, Reusability, Extensibility .   how we will see …

The main concept  of oops is based on the below features
 
1.Objects
2.Classes
3.Abstraction and Encapsulation
4.Inheritance
5.Polymorphism

Lets see one by one these features …

1. Object

In OOP terms an object is an instance of a class and often known as run-time entities having a storage and State associated with it. In object oriented system data is logically represented in the form of a class and physically represented in the form an object or in lay man’s term we can say “you can see the object , but not the class”

Class doesn’t have any memory space hence to work with the data represented by the class we must need to create a variable for the class called as Object. When an object is created using the keyword new, then memory will be allocated for the class in heap (Managed Heap in case of .Net), Known as an instance and its starting address will be stored in the objectin stack. If object is created without new, then memory will not be allocated in heap hence instance will not be created and object in the stack contains the value null and if object contains null, then it is not possible to access the members of the class using that object.

2. Class

A class is simply a representation of a user defined data type of object. It is the blueprint or template that describe the details of object. Taking inheritance into consideration we can say class is a collection of objects of similar type. We can consider Class as the general thing and object is the specialization of general thing. Once class is defined, any number of objects can be created further hence we achieved the re-usability.A Class is composed of three things: Name, Attributes, and operations.
We need to Identify and design a Class based on our requirements by following five Major principles as below.

i. SRP - The Single Responsibility Principle
A class should have one, and only one, reason to change.

ii.
OCP
- The Open Closed Principle -
A class should open for extension but closed for modification.
iii. LSP - The Liskov Substitution Principle-
Derived classes must be substitutable for their base classes.
iv. DIP - The Dependency Inversion Principle-
class should Depend on abstractions, not on concretions.
v. ISP - The Interface Segregation Principle- clients should not be forced to implement interfaces they don't use

The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to external interfaces.
However classes and objects may have various kind of relationship with the external world, those Relationship category can help us to understand the complexity of the system.
Measuring system complexity: We can measure the System complexity with the help of class diagram and evaluating the relationship with other classes simply we can see how many classes can be affected by changing a class. The sum of the affected classes for every class in the system can be the total system complexity.
Relation ships
Instance Level Relations

i. Association

ii.
Aggregation
iii. Composition
Class Level Relations
iv. Generalization
v. Realization

 i. Association
An association is used when one object wants another object to perform a service for it. an Association is kind relationship where objects have their own life time, as per example Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle.. In other way we can say they can exist without each other and both can be created and deleted independently.
As per the nature an association can be bi-directional,uni-directional, Aggregation and Reflexive
 


 


      ii. Aggregation
An aggregation is used when life of object is independent of container object But still container object owns the aggregated object as per example : Team has players, If team dissolve, Player will still exists. In aggregation, a strong bonding is not necessarily true. Lets take our previous example For example, a school owns various departments and each department has a number of teachers . If the Scholl closes, the departments will no longer exist, but the teachers in those departments will exist. This relationship between the aggregate and component is a weak “has a”relationship as the component may survive the aggregate object. The component object may be accessed through other objects without going through the aggregate object. The aggregate object does not take part in the lifecycle of the component object, meaning the component object may outlive the aggregate object. Therefore, a school can be seen as a composition of departments, whereas departments have an aggregation of Teachers.

Aggregation differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.
      iii. Composition
A composition is used where each part may belong to only one whole at a time as per example:. A line item is part of an order so A line item cannot exist without an order. Composition is a kind of association very similar to aggregation except where the composite object has sole responsibility for the disposition of the component parts. The relationship between the composite and the component is a strong “has a”relationship, as the composite object takes ownership of the component.

 

If the composite object is destroyed, all the component parts must be destroyed, or the reference and responsibility of the component part must be handed over to another object. Composition enforces encapsulation as the component parts usually are members of the composite object. Composite relation, more accurate way is to have a one define inside the other class (making it a protected or private class).

  3. Abstraction and Encapsulation

As we saw above with access modifiers ,within a class if a member is declared as private, then that member can not be accessed from out side the class. I.e. that member is hidden from rest of the program. This process of hiding the details of a class from rest of the program is called as data abstraction to achieve security, Also With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes. Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to the outside world and only those functions which are stored in the class can access it.

Encapsulation is used to hide its members from outside class or interface, whereas abstraction is used to show only essential features.

Encapsulation uses five types of modifier to encapsulate data public, private, internal, protected and protected internal(in .net) to create the scope or boundary of abstraction Layer .
 

 4. Inheritance

Instead of recreating new members the new class can be extended from existing class.Inheritance is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance pro vides reusability, like, adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes.the class that is inherited is called as Base class and the class that does the inheritance is called as Derived class.
We can classify Inheritance into 5 categories.
i. Single Inheritance ii.Hierarchical Inheritance iii.Multilevel Inheritance iv.Hybrid Inheritance v.Multiple Inheritance
Its not too complex lets go through a garpical reprenstation of each one that will clear to us.

i. Single Inheritance

Its simple One base class one and child class




ii.Hierarchical Inheritance

One Base class and more than one derived class









iii. Multi Level InheritanceIf a child class has further child derived it from it.




iv. Hybrid Inheritanceits combination of single, hierarchical and multi level inheritances
 


v. Multiple Inheritance

when a derived class is created from more than one base class which is not supported by .net because of circular reference issues.

5. Polymorphism


lets start it from overloading and overriding

By implementing overriding or overloading we actually get the polymorphic nature of the object
Hence the same object behave differently depending up on requirement.
Secondly we can say overloading is compile time and in same class and overriding is run time with different classes or more better we can say design time polymorphism and run time polymorphism .
Also would like to share the idea behind why we called say like this

Overloading::
We create a class and two methods with same name and different parameters

using System;
class OverLoading
{
static void Printme(int x)
{
Console.WriteLine(x);
}

static void Printme(string y)
{
Console.WriteLine(y);
}

static void Main()
{
Printme("stringvalue");
//or
Printme(123);
}
}

Overriding::please see the example below

using System;
namespace overriding
{
class A
{
public virtual void Printme()
{
Console.WriteLine(“hello from class A”);
}
}

class B : A
{
public override void Printme ()
{
Console.WriteLine(“hello from class B”);
}

}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a. Printme (); // this will print: “hello from class A”
b. Printme (); // this will print: “hello from class B”


a = new B();
a. Printme ();// this will print:"hello from class B "
}
}
}

from the above example we can conclude that at run time its being decided which class’s method need to be called ok fine
first thing we know from the example that respective class’s method will be called hence we say run time
but how base class object knows which child class object need to be called at run time and what if i want my child class also need to have a method with the same name as base class already have and marked as virtual...
is not it interesting ??

please see Vtabels.... and method hiding.

http://virtual-functions.blogspot.in/


A Little More inside ::
We must know the purpose of polymorphism is to implement the programming style i.e "message-passing” and in terms of oops we can say to achieve polymorphism means we can assign to an object reference an object whose type is different from the object reference.
As we can write:
 
A objA = new B();
 
For the above statement we know that A and B must have a relation of inheritance and B should be derived from A, ofcourse A may be a class or an Interface.
Lets add few more points like
in static polymorphism we uses the concept of compile time binding(Early binding) in
dynamic/runtime/Inclusion/subtype polymorphism we uses the concept of runtime binding (or late binding) by using hierarchy.
We know how to achieve Static Polymorphism off course by using overloading lets see types of overloading by which we can achieve the same.

1.Method Overloading
2.Constructor Overloading
3.Operator Overloading

So far so good…
 
Now lets divide polymorphism into four kinds and further subdivided into two categories
A.Classical /Universal Polymorphism
Universal Polymorphism relates to the forms of polymorphism that can be applied to all types and they are

 


1. Parametric Polymorphism
2. Inclusion Polymorphism.
 1. Parametric Polymorphism
It is the purest form of polymorphism , which can be is implemented with generics in languages like C# and Java where as in C++ through templates. In other words we can say It allows the type of its parameters to be determined by an implicit(value Type) or explicit type(reference Type) parameter, and we expect the same kind of work from the object irrespective of the type
We can relate it to generic functions such as a Length( ) function which is same for (many)arbitrary types.
Implementation of parametric polymorphism can be done in two ways

1. Specializing the Code: Specializing the code for each object
2. Sharing the Code: Generating common code for all objects.

CLR creates a specialized copy of the native code for each generic type instantiation with a value type, but shares a single copy of the native code for all reference types

Lets simplify the above
If I have a generic class jhankar<T>

I can write jhankar<int> ibj1 = new jhankar<int>( );

or jhankar<string> ibj2 = new jhankar<string>( );

This above one is Specializing for this CLR will create separate copies for each instanceand I f I will write
jhankar<Classabc> ibj1 = new jhankar<Classabc> ( );
this is Sharing, CLR will keep the native code at one point and references for each object
Inclusion Polymorphism or subtype polymorphism indicates that one object can be seen as belonging to many different classes we already discussed.

   B. Ad-hoc Polymorphism
Ad-hoc Polymorphism relates to polymorphic features that are restricted to only some types and is divided into Overloading and Coercion.
Overloading : where we have one identifier which is capable identifying many different methods and compiler is responsible for choosing the appropriate one to use based upon call.
Coercion: is the term used to describe the conversion (implicit) of a data from one type to the expected type. For example,
coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory.
double d=10.10;
int i=5;
if (d > i) d = i;
Keep on Exploring..

.Net Framework
CLR: Common Language Run time
§ CTS: Common Type Specifications
§ CLS: Common Language Specifications
§ GC: Garbage Collector
§ FCL: Framework Class Library
§ IL: Intermediate language § ILDASM:IL Disassembler 
§ ILASM:IL Assembler(ILAsm.exe)
§ Modules
§ Assemblies
§ JIT: Just in Time
§ GAC: Global Assembly Cache

No comments:

Post a Comment