Sunday, January 16, 2011

Constructor

Constructor
Constructor is a special method without any return type and have same name as class name. Constructor is used to initialize an object of a class and it runs or executes automatically when you create an object. Constructors are called only once per creation of an object while regular methods can be called many times. Constructor can be private, public, static and protected. We can also overload constructor.

In c# constructor are called using new keyword.
Car objcar = new Car();
When you use new keyword then object is created and runtime will construct that object by using the definition of the class. Then it grab a piece of memory and fills with the fields (variable or methods) defined by the class and then a constructor is invoked to perform any initialization required.

Constructors are generally of following types
  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Default Constructor
When you create class without any constructor then compiler will provide you parameterless constructor with no body that parameterless constructor is called default constructor.

To explain default constructor we will make two program, in first program we will use default constructor which is provided by compiler and secondly we will create our own default constructor . 

We can't see default Constructor provided by compiler (but it is present in the class) thats why we will make our own default constructor to show that both are same.

First Program

You can see that we have two variables in class Name and LastName but not constructor but when we create an object of class its working properly. That means there is a default constructor in class provided by compiler but we can't see it.

Second Program

In this program we have two variables in class Name, LastName and a default constructor. When we will create an object the result will be the same as first program.
  
Parameterized Constructor
Constructor that accepts arguments when object is created is called parameterized constructor. Parameterized constructor is not provided by compiler you have to create this constructor. You can use parameterized constructor when you have to initialize data members of a class when object is created.


You can see Human constructor with two parameters Name and Lname. When we create an object we have to provide parameters (e.g. Human objH = new Human("James","Bond");) then Name = James and LastName = Bond will be assigned.

Copy Constructor
Copying values of one object to another object is called copy constructor. If you want to copy values of existing object to another new created object then you have to write method yourself because c# does not provide copy constructor.



We have create two object objH and objAnotherHuman, and will copy data of objH to objAnotherHuman. First we have create objH object and pass parameter(James, Bond) . It means that objH have Name = James and LastName = bond. Now we will create another object objAnotherHuman and will pass objH as parameter . Now copy constructor will copy obj.Name(i.e James) to objAnotherHuman.Name and obj.LastName(i.e Bond) to objAnotherHuman.

If you do not understand what happens or how values are assign in copy constructor then run the program in debugging mode 


Read about Private Constructor, Constructor Overloading, Constructor Chaining

How To call Constructor from another Constructor

Saturday, January 15, 2011

Encapsulation

Encapsulation
The concept of sealing data and methods into an object is known as encapsulation. Its ability is to hide information and internal implementation from the users. Information hiding doesn’t mean to hide information but it means that it gives limited access to user. Access modifiers provides accessibility level for user.



Examples
If you want to meet the president of your country you can’t go directly to meet president. Guard or Security of president will check you and if you have appointment or you have access then you can go to meet him. That’s what encapsulation does. Its guard your data not hides it.  

Take an example of car. All of us drive car when we sit in car and insert key in it and turn it to start the car , the car get started but we don’t know how its starts. We don’t know the internal working of the car. The internal implementation is hidden from the user.


A tracker in a car that helps us trace our car when someone steals our car, so we just let the tracking service provider company know that my car has been stolen I know they can trace it but keep it hidden how are they going to trace it 

Public Access Modifier


We can only access Name because it is public.

Private Access Modifier
To access private variable we have to make property for that variable which will guard the variable and we can access private variable via that property.

Now we can access EngineNo variable via EngineNo1 property.





Protected Access Modifier
Protected variables can be access by inherited class. Let make another class which will inherit clsCar.




Friday, January 14, 2011

Polymorphism

Polymorphism
Polymorphism means having many shapes. Polymorphism allows improved code organization and readability. Its ability of an object is to respond differently to the same message. When a message is send to an object even though we don’t know what specific type it is, but the right thing happens, that’s called polymorphism.

Types of Polymorphism
  • Compile-time polymorphism (early binding)
  • Compile-time polymorphism is also called method overloading.

Compile-Time Polymorphism
Compile-time or Early binding is achieved by Overloading which allows us to have two or more methods in the same class have the same name with different parameters

Example:
We will create a method that will calculate the square of a given number having same name but different data type.


In this program we have use different methods having same name but different parameters this is called overloading.

Run-time polymorphism

Run-time polymorphism is achieved by method overriding.
Overriding allows us to have methods in the base and derived classes with same name and same parameters.

Example:
We have created three classes clsLine, clsTriangle, clsCircle derived from base class clsShapes. clsShapes contain draw() method and clsTriangle and clsCircle contains fill() method. We have declared draw() method as virtual method(virtual keyword is use to modify properties and allow method to be overridden ) so we can override that method  in derived classes by modifying implementation of virtual method with respect to derived classes. So the method to be executed is selected dynamically during run-time.


Now make an object 
clsShapes objShape = new clsTriangle();
and call method draw().


In this picture objShape.draw() is called and you can see the result it says "draw from clsTriangle" which means that draw method is called from clsTriangle class. We can determine the result when we run this program but not on compile-time.

Inheritance

Inheritance
Inheritance is a process of creating new classes from previous defined classes.
Inheritance is the addition of behaviour (i.e. methods) and attributes (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for Code reusability. In c# we can inherit only one class at a time but can inherit many interfaces.
The existing class is called the parent class and the derived class is called the child class. We can also say that Inheritance is the process in which the derive class inherit or receive characteristics from base class same as a child inherits characteristics from their parents. 
When a derive class is inherits from base class, then derive class contains all the behaviour (i.e. methods) and attributes (i.e. variables) of the base class and derive class adds some new characteristics of its own. If base class makes any changes then it’s propagated to all derive class that inherit from them. Unless explicitly overridden. 

Generalization and Specialization are two terms used in inheritance. clsShapes is generalize form and clsLine, clsTriangle and clsCircle are specialize form of clsShapes. Because they also have there own special methods which makes them different from another class. Generalization is from bottom to top and Specialization is from top to bottom.

We can inherit our class from classes as well as interface:

Inheritance between classes is called Implementation inheritance
Inheritance between classes and interface is called Interface inheritance


Implementation Inheritance
In implementation inheritance we inherit class from class. I am made a class clsShapes which is base class and clsLine, clsCircle and clsTriangle are derived class of clsShaped (inherited from clsShapes).

In above picture I have made a class clsShapes which contains draw method and class clsCircle, clsLine and clsTriangle which have fill method and is inherited from class clsShapes.

Here you can see I have made an object of clsCircle which is inherited from class clsShapes. objcircle is object of clsCircle. When you write objcircle(.) then you will see all those variables and methods which clsCircle have like in clsCircle we have draw and fill method. Draw method was not in clsCircle but we have inherit clsShapes that's why we can use draw method in clsCircle.

Interface inheritance
Now we will inherit class with interfaces.Take the same example we use in implementation inheritance. I have made a interface named Ishapes and its contain fill method. clsCircle and clsTriangle are inherited from Ishapes.


Now when we instantiate object of clsCircle or clsTriangle we can use fill methods and we can use same as we have used fill method in implementation inheritance. but in interface we don't have to write methods everytime in every class we just make a interface and inherit it and then use it by giving body of all that method which are in interface.

Thursday, January 13, 2011

Classes and Objects

Classes and Objects
It’s difficult to understand class without objects and objects without class. That’s why I will be explaining objects and classes with help of each other. It’s difficult to understand object and classes concept for beginners. For that I will use different real life examples to make it easy for the readers to clear this concept.

Understanding Classes

A class is a model or pattern from which an object is created. The class defines the data types that will be held in an object, and defines code for the functions. After defining a class an object is created from it. The process of creating object from a class is called instantiation. We can also say that class is a map which describes the structure of an object.

For Example. You want to construct a building. First of all you will design a map and will describe its structure. That map is called class. After it you will construct building according to that map. The building you have constructed is called object and will have all those structures describe by its class. The Building can be a hospital, shopping Mall or schools. We can’t live in map because it is not a physical entity but we can live in building because it’s a physical entity.


Structure of Class
Understanding Objects
An object is anything. A class consists of a category of things. An object is a specific item that belongs to a class; it is instance of a class. The class defines the characteristics of its object and the methods that can be applied to its object.
An object contains attributes (i.e. variables) and behaviour (i.e. member functions). Attributes are the data associated with the object and the methods are the functions which operate on the data. Object is the physical entity of the structure described by its class

Consider the example of a class MyCarCompany. The class MyCarCompany describes all car objects (i.e. is attributes and behaviour). You can’t use MyCarCompany class but you can use objects of MyCarCompany. Let suppose objects of MyCarCompany are ObjSkyline, ObjSupra, and ObjGallardo. Now you can use all of these objects of class MyCarCompany. You can’t say that I am driving MyCarCompany instead of it you can say I am driving an ObjSkyline which belongs to MyCarCompany.

Take anonther example, MyDish is a class. You can use the MyDish objects or you can hold MyDish objects and that you can eat from it. MyMug is an object or an instance of the class MyDish. We can use the object of MyDish class but can’t use MyDish class. 



Thats how we instantiate a class. ClassnObject ObjClassnObject = new ClassnObject();
After instantiate we can use attributes and behaviour of class by using dot(.) with Object like I did in picture above. ObjectClassnObject. now you can see small window with some attributes and behaviour that we have define in class. Have you noticed one thing. CreditCard variable is not there because it was private but property of CreditCard is there on top.

















Saturday, January 8, 2011

Object Oriented Programming (OOP)

Object Oriented Programming (OOP) 
Object oriented programming (OOP) deals with thing called 'objects'. Objects are just extremely functional ways of organizing information. Object in an OOP language are combinations of code and data that are treated as single unit.

Understanding Whole Mechanism of OOP
To see object oriented working in action, consider your everyday life. The 'real world' is full of objects. Take a Door for an example, the door needs to be opened and closed, and you pass message by turning its knob. The same message (like turning knob) will have different meanings when you apply to different object. If you turn the knob of radio it will act differently than door, same as with window and desk. But all of them have the same function called 'open' but different behaviour. A new door with a stained glass window inherits most of its quality from a standard door. When you use a door, you usually do not care about the latch or hinge, construction features, and you don't have access to the interior working of the knob or what may be written on the inside of the door panel.
Basic principles of object oriented programming are

TypeCasting ( Implicit and Explicit )

Type Casting
Casting means to throw or turn a certain direction or state. Type casting is a mechanism to convert data of one type into data of another type (e.g. int to long, int to float, long to double, and so on).
If you have done coding in c# than you should already know that it is common to assign a value of one integer into another type of integer. If the two types are compatible (agreed with each other) than casting is possible. If you want to assign an int value to a long variable it is possible because both data type agreed and this is called implicit type casting. If you want to assign double to byte (incompatible types) than it’s possible to change the casting between incompatible types to achieve this you must use a cast to perform explicit casting. Two types of typecasting are:-

Implicit Typecasting
  • Converting data of small data type into large data type (e.g. int to long, byte to int).
  • To achieve implicit casting both types should compatible and the destination type must be larger than the source type.
  • Implicit casting is performed automatically by c# compiler for you.
  • No loss of data in implicit casting.



Typecasting
Implicit Typecasting
Explicit Typecasting


  • Converting data from large data type into small data type (e.g. int to byte, long to int)
  • This Conversion will not be perform automatically because the destination is smaller than the source.
  • You must use a cast to perform explicit casting.
  • Chance of losing data.


Typecasting
Explicit Typecasting


Typecasting
Result 

If not using cast then?
If not using cast when casting incompatible types then you will be facing some problem shown in picture below.
Typecasting
Errors when not using cast
Both types (e.g. short to byte, int to short, float to int) are not compatible with each other that’s why it requires cast.