In this part of tutorial you will learn about the class and object and also its benefit in object oriented programming.
Object and class are two pillars in Object Oriented Programming (OOP). OOP is all about object. In this part we will learn about these terms.
Class is a very common word around us. When you talk about separation, or about classification, you indirectly talk about class. One can understand class as a container which consist of variables, properties, constructor and methods. In simple word, class is a blueprint for an object. Class is more or less same as a struct. There is a good article written on this. Please click on the link to read more.
A class is simply a representation of a type of object; think of it as a blueprint that describes the object - MSDN
We create a class with class keyword. This is a simple class with a constructor and a method inside it.
public class Apple
{
public Apple()
{
Console.WriteLine("Entered into the constructor...");
}
public void Display()
{
Console.WriteLine("Entered into Display method...")
}
}
Everything we see around us, is an object. It can be understand as a thing. Let suppose I have an apple in my hand. Here apple is an object. It is a fruit so object type will be fruit. Now let suppose, I have five 5 apple so I have five objects. Here apple is a class and I have five object of class apple. In OOP term- An object is an instance of a class and is a block of memory that is configured as per class's blueprint. We can create multiple instance of same class. We use new keyword to create an object.
An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection - MSDN
//Created object of class Apple. We use new keyword to create object.
Apple apple = new Apple();
Though both object and instance are same but there is a little difference between these two terms. Let's understand this with a small example.
Apple objApple; //Defined a variable objApple of type Apple class
objApple = new Apple(); //Using new keyword created an object of this type
objApple.Display(); //Called method Display() through the instance objApple
Hoping you are pretty much clear on object and instance from above example. In above example an object is created using new keyword and objApple is the instance of that object.
In this part of tutorial you have learnt basics about class, object and also about instance. There is one more term similar to class, we call it as Struct but there are few differences between these two. Please click on the link to read more. In the next part of the tutorial we will learn about Interface and its use in OOP.