In object-oriented programming (OOP), object and class play an essential role; In fact, OOP is based on object and class.
Definition of Objects
An object is any real-time entity which has some properties (State) and can perform some task (Behaviour).
For example, Mobile is an object; it has some properties (State) like length, colour, weight, etc. and it perform some task (Behaviour) like call, message, etc.
In programming, objects are conceptually like real-world objects. An object contains data in the form of properties or fields (State) and the methods (Behaviour).
Definition of Class
Class is like a template or blueprint of an object. It is a collection of properties or data fields (State) and the method of an object (Behaviour).
Let’s understand this by using the same example of Mobile.
So Mobile has a name, length, color, weight, camera, and Mobile can perform operations like call, message, take a photo, etc.
Here is a sample C# source code of Mobile Class
class Mobile
{
public string Name { get; set; }
public double Length { get; set; }
public string Color { get; set; }
public double Weight { get; set; }
public void Call()
{
}
public void Message()
{
}
public void Photo()
{
}
}
The above code can be used as a generic template of a Mobile. Using the same template, we can create another mobile with a different name, length, color, or weight.
var appleMobileObject = new Mobile()
{
Name = "IPhone 6",
Color = "Black",
Length = 7.5,
Weight = 36.12
};
var nokiaMobileObject = new Mobile()
{
Name = "Nokia Pro",
Color = "Red",
Length = 5.5,
Weight = 25.00
};
var samsungMobileObject = new Mobile()
{
Name = "Samsung Galaxy",
Color = "White",
Length = 10.5,
Weight = 37
};
In the above example, we see that we have created different mobile objects using the same template. We produce different instances of a class using an object. An object can access all properties (Name, Color, Weight, Length) and methods (Call, Message, Photo) of a class.
In other words, we can also say that class defines a data type, which contains data members and methods, which can be accessed by creating an object of that class. The object of the class is also called an instance of that class.
You can read more about Object-Oriented Concepts
Helpful Resources
- Free online class & object multiple choice question (MCQ) quiz based on C#.
- Object-Oriented Overview
- Encapsulation in object-oriented programming
- Abstraction in object-oriented programming
- Inheritance in object-oriented programming
- Polymorphism in object-oriented programming
- Object-oriented online multiple-choice question (MCQ) free quiz