Sunday 30 November 2014

Object Oriented Programming

What is Class ?
A class is a template which contains a property  and method. It is a blueprint of an object. It  is a central point of OOP which describes a set of objects with common behavior.

What is an object ?
Objects is an instance of a class which can access the method or properties of the class from which the object is created.

What is encapsulation ?
Encapsulatin can be define as follows :
1. The process of binding a data and method into a single unit are known as encapsulation.
2. It is a process of hiding all the internal details of an object from the outside world.
3. Encapsulation is the ability to hide the data and method from outside the world and only expose data and method that are required.
4. Encapsulation is a protective barrier that prevents the code and data being randomly accessed by the other code or by outside the class.
5. It gives us maintainability, flexibility and extensibility to our code.
6. Encapsualtion makes implementation inaccessible to other parts of the program and protect from whatever action might be taken outside the function or class.
Ex :     
Public class Test
{
string   Name;
int   Age;
int  Total;
  Public string GetName()
{ {
name =”Bhimsen”;
}

Public  int Age()
{
age = 25
}

Public int getTotal(int a, int b, int c)
{
total = add(a,b,c);
}
private add(int x, int y, int z)
{
return  a+b+c;
}
}
Explanation : In the above example Test  class binds the Data and Method into a single unit (Class). GetName,GetAge and GetTotal is a public function which can be exposed by an object. But GetTotal Method using  Add() method which is private which only can use by getTotal not outside the world. So Encapsulation is the ability to hide the data and method from outside the world and only expose data and method that are required.

What is Abstraction ?
Abstraction is a process of hiding the implementation details and displaying the essential features. It is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface). 
Example : A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.
Note : Abstraction is a concept of hiding the internal details of the object. And encapsulation is an implementation of the abstraction.

What is Constructor ?
A constructor can define as follows:
1. A constructor is a mechanism which initialize the data and object  of its class.
2. It  is special method because its name is same as the class name.
3. They do not have return type not even void.
4. It cannot be inherited.
5. Constructor can be invoked whenever an object of its associated class is created.
Note :  Every class always contains atleast one constructor. If there are no constructor in class, C# automatically provide one for you, this is called default constructor.

What is Polymorphism ?
As the name suggested Polymorphism, It is made by Two words “Poly” and “Morph”. Poly means “Many” and morph means “Forms”. Hence polymorphism is a technique in which a single identifiers (Data, Method or object etc.) have a different forms. It has an ability to process object differently on their data types. It also has the ability to redefine the method for derived class.
There are two types of polymorphism. They are :
1. Compile Time Polymorphism ( Early Binding)  - Function Overloading  and Operator Overloading.
2. Runtime Polymorphism (Late Binding)   -  Method overriding and Virtual Function.

What is Function Overloading ? When and why we use it?
Function overloading is a mechanism in which a class contains two or more than two method with the same name but with different argument. It comes under the compile time polymorphism.
EX :        
class bits
{
void speak()
Console.WriteLine(“Hello”); 
}
void peak(string s)
{
Console.WriteLine(“Hello {0}”,s); }
}

Explanation : In the above example There are two “Speak” method and both has a different argument(0,1).

When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.

What is Function Overriding ?
Overriding is a mechanism in which a More the one method having the same argument but different class(Base, Derive).It is use to enhance or customize the functionality of the Function. Means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/override keywords.Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.

Example: 
// Base class
public class BaseClass
{
public virtual void Test1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Test1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass(); 
objDC.Test1();
 // calling the baesd class method
BaseClass objBC = (BaseClass)objDC; 
objDC.test1();
}
}

Output :
Derived Class Method
Derived Class Method

What is Inheritance ?
Inheritance is a mechanism in which one class inherits the data or method into the another class.The class whose data or method inherited are known as Base Class,Parent class or Super class. and the another class who inherits the data or method are know as Derive class, child class or subclass class.
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                                 
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                                 
Public class ChildClass: BaseClass
{
                                 
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
   
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}


In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

How method overriding is different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

What is Inheritance ?
Inheritance is a mechanism in which one class inherits the data or method into the another class.The class whose data or method inherited are known as Base Class,Parent class or Super class. and the another class who inherits the data or method are know as Derive class, child class or subclass class.
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                               
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                               
Public class ChildClass: BaseClass
{
                               
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
 
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}


In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

Or

Inheritance can be also define as follows :
1. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.
2. The Class whose methods and variables are defined is called super class or base class.
3. The Class that inherits methods and variables are defined is called sub class or derived class.
4. Sometimes base class known as generalized class and derived class known as specialized class
Keyword to declare inheritance is “:” (colon) in visual c#


Benefits of using Inheritance
Once a behavior (method) or property is defined in a super class(base class),that behavior or property is automatically inherited by all subclasses (derived class).
Code reusability increased through inheritance
Inheritance provide a clear model structure which is easy to understand without much complexity
Using inheritance, classes become grouped together in a hierarchical tree structure
Code are easy to manage and divided into parent and child classes


What is an Interface ? When and why we use it ?
1. An Interface is a group of constants and method declaration.
2. C# supports multiple inheritance through Interface.
3. Interface states “what” to do, rather than “how” to do.
4. An interface defines only the members that will be made available by an implementing object. The definition of the interface states nothing about the implementation of the members, only the parameters they take and the types of values they will return. Implementation of an interface is left entirely to the implementing class. It is possible, therefore, for different objects to provide dramatically different implementations of the same members.

When to Use an interface

if we want to Implement same signature in different class then we can use it.
consider a company where there are staffs and supporting staffs. All will be given salary but staff salary calculation is different from supporting staff salary calculation. here is how it is implemented

public interface ISalary
    {
        decimal CalculateSalary();
    }
public class Staff : ISalary
    {
       public  decimal CalculateSalary()
        {
            //Staff salary calcuation logic        
        }
    }
    public class SupportingStaffs :ISalary
    {
      public  decimal CalculateSalary()
        {
            //Supporting Staff salary calcuation logic
     
        }
    }

What is an abstract class ?

An abstract class can de define as follows :-
1. An abstract class is a class that cannot be instantiated. This implies that you cannot create an object of the abstract class.
2. It exists extensively for inheritance and it must be inherited.
3. An abstract class may contain abstract as well as non abstract member.
4. The abstract method in abstract class may contain definition and declaration.
5. A class with abstract member must be abstract.
6. You must declare at least on abstract method in the abstract class.
7. Abstract class is declared using the abstract keyword.
8. An abstract class is always public.

When do you absolutely have to declare a class as abstract?

1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2.  When at least one of the methods in the class is abstract.

Difference between Abstract class and interface.

1. In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.
2. In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.
3. A class can extends only one abstract class where as a class can implement several interface.
4. Abstract class should have subclass. An interface must have implementation by classes.
5. There  can be a constructor for an abstract class. But interface doesnot have constructor.

Or

Abstract Class: 
1. A class can extend only one abstract class
2. The members of abstract class can be private as well as protected.
3. Abstract classes should have subclasses
4. Any class can extend an abstract class.
5. Methods in abstract class can be abstract as well as concrete.
6. There can be a constructor for abstract class.
7. The class extending the abstract class may or may not implement any of its method.
8. An abstract class can implement methods.

Interface 
1. A class can implement several interfaces
2. An interface can only have public members.
3. Interfaces must have implementations by classes
4. Only an interface can extend another interface.
5. All methods in an interface should be abstract
6. Interface does not have constructor.
7. All methods of interface need to be implemented by a class implementing that interface.
8. Interfaces cannot contain body of any of its method.

What is difference between structure and class?
1    1.  Structure is a value type and class is a reference type.
2    2. Structure allocates memory on stack where as class allocates memory in heap.
3    3. Structure does not support inheritance where as class supports inheritance.
4    4. Variable of structure can not be null but the variable of class can be assign null.
5    5. Structure does not requires constructor where as class must have at least one constructor.
6    6. We cannot put sealed/abstract modifier before the structure. But class can do it.
7. What is pure virtual function?
8. It  is a function that must be overridden in derived class and need not be defined. A virtual function is declare to be “pure” using the  “=0”.

Some OOP’s Terms with explanation.

Static Method :  Static method is a class level method that does not require an object to access the method.

Static Field : This field indicates that, the field should store only once. No matter how many instance of the class we created.

Virtual keyword : A virtual keyword indicates that, a member can be overwritten in the child class. It can be applied to method , properties, index and events.

New  Modifier : The new modifier hides the member of base class.

Sealed modifier :
   1.  Sealed type cannot be inherited.
   2.  Sealed modifier can be applied to instance method, properties , indexes and events.
   3.  It cannot be applied to static member.

    *    Static , value type & interface does not support abstract modifier.
    *    Static member cannot be abstract.

What is the relationship between a class and an object?

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the cass. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto. The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

What is the difference between procedural and object-oriented programming?
Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables. Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public, private, internal, protected, and protected internal.

What is a static constructor?
Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created. The static constructor has the following features:
No access specifier is required to define it.
You cannot pass parameters in static constructor.
A class can have only one static constructor.
It can access only static members of the class.
It is invoked only once, when the program execution begins.

Difference between new and override keyword

Let me explain this through code. 

namespace BaseDerive
{
    public partial class Form1 : Form
    {
        public Form1()
      {
            InitializeComponent();
        }
   private void Form1_Load(object sender, EventArgs e)
   {
            BaseClass b = new BaseClass();
            b.func1();
            DeriveClass d = new DeriveClass();
            d.func1();
            //Calls Base class function 1 as new keyword is used.
            BaseClass bd = new DeriveClass();
            bd.func1();
            //Calls Derived class function 2 as override keyword is used.
            BaseClass bd2 = new DeriveClass();
            bd2.func2();
        }
    }
    public class BaseClass
    {
        public virtual void func1()
        {
            MessageBox.Show("Base Class function 1.");
      }
        public virtual void func2()
        {
            MessageBox.Show("Base Class function 2.");
       }
  public void func3()
        {
            MessageBox.Show("Base Class function 3.");
        }
    }
    public class DeriveClass : BaseClass
    {
        public new void func1()
        {
            MessageBox.Show("Derieve Class fuction 1 used new keyword");
        }
        public override void func2()
        {
            MessageBox.Show("Derieve Class fuction 2 used override keyword");
        }
        public void func3()
        {
            MessageBox.Show("Derieve Class fuction 3 used override keyword");
        }
    }
}

This is a window application so all the code for calling the function through objects is written in Form_Load event.
 
As seen in above code, I have declared 2 classes. One works as a Base class and second is a derieve class derived from base class.
 

Now the difference is
 

new: hides the base class function. 
Override: overrides the base class function. 

BaseClass objB = new DeriveClass();

If we create object like above notation and make a call to any function which exists in base class and derive class both, then it will always make a call to function of base class. If we have overidden the method in derive class then it will call the derive class function.
 


For example… 
objB.func1(); //Calls the base class function. (In case of new keyword)

objB.func2(); //Calls the derive class function. (Override)

objB.func3(); //Calls the base class function.(Same prototype in both the class.)

Note: 
// This will throw a compile time error. (Casting is required.) 

DeriveClass objB = new BaseClass(); 


//This will throw run time error. (Unable to cast) 


DeriveClass objB = (DeriveClass) new BaseClass(); 

What are queues and stacks?

 Stacks refer to a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, elements are inserted (push operation) and deleted (pop operation) from the same end called top. Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.



No comments:

Post a Comment