Pages

OOPS


OOPs

Introduction:

Object Oriented Programming (OOP) is to remove the some of flaws present in procedure Oriented Programming approach. OOPs treat data as a critical element in the program development. OOPs allows decomposition of a problem into a Number of entities called objects and then builds data and Functions around these objects

Definition:

Object-oriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions


Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts. The Purpose this article is to demonstrate the basic concepts of the OOP

 

Object:


Objects are the basic building blocks of an object-oriented programming. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle

 Each object can perform a set of activities. The set of activities that the object performs defines the object's behavior.

Object is simply the Instance of class.

Class:

The most common definition of the class is Collection of Similar type of objects or it is template for an object

A class is collection of member variables and methods. A class contains static fields and non static fields (instance).

Creating an instance means creating a copy of all the instance fields in the memory.
Each instance has separate copy of the data. The value of instance fields will be change for each object

But static fields have common memory in the class. The value of the static fields does not change with object.

We cannot use static fields with the reference of object. We can use them with name of class.

If we mention static key with the class name, all fields in class should be static.

AccessSpecifiers:

Access Specifiers define the access to class members from the same class and from other classes. The most common access

 Keywords are:
 Public: Allows access to the class member from any other class.
 Private: Allows access to the class member only in the same class.
 Protected: Allows access to the class member only within the same class and from                   inherited classes.
Internal: Allows access to the class member only in the same assembly.
Protected internal: Allows access to the class member only within the same class,    from inherited classes, and other classes in the same assembly
Static: Indicates that the member can be called without first instantiating the class.


Abstraction & Encapsulation:

The wrapping up of data and functions into a single unit (called class) is known as encapsulation. The data is not accessible to the outside world, and only those functions, which are wrapped in the class, can access it. These functions provide the interface between the object’s data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding.
        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 such as size, weight and cost, and functions to operate on these attributes.

Constructors:
Constructor is a method in the class which gets executed automatically at the time of object creation. The name of the Constructor is same as Class name. Generally we put the initialization code in Constructor.

A class contains any number of Constructors but each class contains at least one constructor (default Constructor).

Example:

   Public class MyClass
  {

      // Constructor
      Public MyClass
      {
           // initalization code (this is Optional)
      }

 }

  Syntax: Classname Obj1 = new ClassName ();

        Ex: MyClass obj1 = new MyClass ();

The Above statement calls the constructor. While creating the object


Constructor Overloading:

C# supports the Constructor Overloading. That is one class can contain more than one constructor with set of parameters.

Example for Constructor Overloading

Public class MyClass
  {

        Public MyClass()
        {
            // constructor with no parameter
            // default Constructor
        }
        Public MyClass(int num)
        {
             // constructor with one parameter
        }
        
         Public MyClass(int num,stirng name)
        {
           //constructor with 2 parameters
         }
 }

In above class we have 3 constructors. Now the question is which constructor gets executed at the time of object creation?

Which constructor gets executed is depend upon the way we create the object

Example:

1)     MyClass Obj1 = new MyClass();
             // this Calls the default constructor

2)     MyClass Obj2 = new MyClass(12);
// this calls the constructor with one parameter  
   
3)      MyClass Obj2 = new MyClass(12,”C#”);
             // this calls the constructor with 2 parameters
    
From the above example we can understand that, which constructor gets executed is depend upon the parameters what we pass when we create the object.

Types of Constructors:

There are 3 types of constructor
1)     Public Constructors
2)     Private Constructors
3)     Static  Constructors

1)    Public Constructors:  Public constructors are used to instantiate and initialize the fields during object instantiation. These constructors are with public access Specifier
                  The above shown all examples are belongs to the Public Constructors only
2)     Private Constructors: Private constructors, the constructors with the "private" access modifier. Private constructors are used to restrict the instantiation of object using 'new' operator. This type of constructors are mainly used for creating singleton object
               But we have set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining.

Example:

           Public class MyClass
            {
                  private MyClass()
                   {
                           // Private Constructor
                           
                  }
                 Public MyClass(int num)
                  {
                       // constructor with one parameter
                  }
        
                 Public MyClass(int num,stirng name)
                 {
                         //constructor with 2 parameters
                 }
          }

              Creation of a object
                  MyClass Obj1 = new MyClass (10); // Creates an object
                  MyClass Obj2 = new MyClass (); // gives an error

3)     Static Constructors:
               This is a new concept introduced in C#. By new here, I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
The syntax of writing the static constructors is also simple
           Public class MyClass
            {
                   Static MyClass()
                    {
                         // code for intializing the static variables
                     }
             }
Notes for Static Constructors:
  1. There can be only one static constructor in the class.
  2. The static constructor should be without parameters.
  3. It can only access the static members of the class.
  4. There should be no access modifier in static constructor definition.

Inheritance:

This is one of most important concept in Object Oriented Programming (OOP).

Definition: Creating a new class from existing class is called inheritance.

The new will inherit the properties of existing class. The existing class is called as parent class and new class is called as Sub class. The entire .NET framework is built on this concept; the object of every class is inherited from System.Object class
The following OO terms are commonly used names given to parent and child classes in OOP:
  • Superclass: Parent class.
  • Subclass: Child class.
  • Base class: Parent class.
  • Derived class: Child class
I will explain with an example. Now I am creating an Animal class that contains only one method Greet ()
Public class Animal
{
   Public void Greet ()
   {
           Console.writeline (“Hello, I am animal”);
   }
}

Now I am creating a Sub class Dog for Animal class as follows

Public class Dog: Animal
{
  
}
Dog class is created with the colon Animal class. This represents the Dog class is sub class for Animal class. I am creating objects for the both classes

Animal animal1 = new Animal ();
  animal1.Greet ();
Dog dog1 = new Dog ();
   dog1.Greet ();

When we execute the code both animal1.Greet () and dog1.Greet () methods calls the Greet method from Animal Class, here we can notice that even though we have not define Greet method in Dog class, dog1.Greet () able to call the Greet method form Animal class.

Base keyword:

The base Keyword is used to cal the base class methods form the derived class methods.
See the below example

Public class Dog: Animal
{
    Public void Greet ()
         {
             base. Greet (); // this statement calls the Greet Method from Animal class
              Console.writeline (“this is from Dog class”);
          }

}

Inheritance can be classified to 5 types:
  1. Single Inheritance            
  2. Hierarchical Inheritance
  3. Multi Level Inheritance
  4. Hybrid Inheritance
  5. Multiple Inheritance 
1. Single Inheritance

when a single derived class is created from a single base class then the inheritance is called as single inheritance.

2. Hierarchical Inheritance

When more than one derived class are created from a single base class, then that inheritance is called as hierarchical inheritance.

3. Multi Level Inheritance

when a derived class is created from another derived class, then that inheritance is called as multi level inheritance.

4. Hybrid Inheritance

Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.

5. Multiple Inheritance

when a derived class is created from more than one base class then that inheritance is called as multiple inheritance. But multiple inheritance is not supported by .net using classes and can be done using interfaces.

Now the Question is why C# not supports the multiple inheritance? To know the answer, first we have to know the behavior of Constructor in Inheritance

Behavior of Constructor in Inheritance

 When we create the object to the Sub class, instead of executing subclass constructor first, the default constructor of Base class will be executed automatically. I.e. base class is initialized before initializing the sub class.

Let us see an example

// base Class
Public class MyBaseClass
{
   Public MyBaseClass ()
    {
         // code for Base class constructor
    }
    Public MyBaseClass (int Age)
    {
         // Code for second base class Constructor
    }
}

// Sub Class
Public class SubClass ()
{
    Public SubClass ()
    {
         // code for sub class constructor
    }
    Public SubClass (int Age): base (Age)
    {
         // Code for second base class Constructor
    }
}

Create Object for sub class

->   SubClass obj1 = new SubClass ();

The sequence of execution
1)     calls MyBaseClass()
2)     calls  SubClass ()

Even though we don’t cal the base class constructor, the default constructor of base class will get executed automatically.

รจ     SubClass obj2 = new SubClass (10);

The sequence of execution
1)     calls MyBaseClass(int Age)
2)     calls  SubClass (int Age)
base (Age) calls the constructor from the base class from derived calls

So if C# supports multiple inheritances, when we create object for the sub class that derived from more than one class. Which class constructor it has to call before calling sub class constructor?

And how can us cal remaining classes’ constructor. That is why c# does not support the multiple inheritance with classes.


Polymorphism


Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. It allows the object to represent in multiple forms.

It is one of the fundamental concept it OOP

Polymorphism provides following features: 
  • It allows you to invoke methods of derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called through the same name.
  •  
Polymorphism is of two types: 
  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding
Compile time polymorphism/Overloading:

Compile time polymorphism is method and operators overloading. It is also called early binding.

In method overloading, different functions have same but performs different task based on the Parameters.

Example:

void area (int side);
void area (int l, int b);
void area (float radius);

Above 3 methods have same name, but different parameters.

Runtime polymorphism/Overriding:

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.

Virtual Functions
Virtual functions implement the concept of polymorphism except that you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use the override keyword.


Example:
Class A
{
public virtual int A();
}

Class B:A
{
public override int A()
{
   //Implementation
}
}






   


                                                                    



No comments:

Post a Comment