In the above figure, to the left you can see a class called human beings. It is just a dummy class showing attributes a human would possess. As you can see a class has no existence. Instead objects have an existence. A class jsut defines what properties and behavior an object of its type would bear. You can see two objects being defined here. As you can see that the objects supply particular values to each attribute of its class. Consider for example one of the objects,
Name: Bilal
Ethnicity: Asian
Gender: Male
Age: 22
Hair color: Brown
As you can see that this object of class human beings has supplied particular values to the attributes that human beings possess. He has a particular name, a particular ethnicity, a particular gender , age and a specific hair color.
Now lets get specific to programming and implement this class called human beings. In the class we can define attributes and behavior that an object(Instance) of its type would possess.
C# is the language being used here.
Class Human_Beings {
public string name;
public string Ethnicity;
public string Gender;
public int Age;
public string Hair_Color;
//these are some randomly specified attributes
// now lets define some behavior in terms of methods(functions)
public void Talk()
{
.....
}
public void Walk()
{
.....
}
}// class ends here
Now lets create an object of this class, just like when we define any variable of type INT we name the variable such as int x, int count, etc. In a similar fashion an object being a variable of the class that defines it needs to have a variable name or an Object reference.
When type is int:
int x;
When type is Human_beings:
Human_beings obj1;
Initialize the int:
x=10;
For objects having so many attributes, we instead call a function called Constructor that does the initialization for us,
obj1 = new Human_beings();
// lets define the attributes
obj1.Name="Bilal";
obj1.Ethnicity="Asian";
obj1.Gender="Male";
obj1.Age=21;
obj1.Hair_color="Brown";
/*now the above code has created an object of type Human_beings pointed to by reference called "obj1" and having the attributes as defined above*/
I hope this article helps the beginners in understanding the basic difference between a class and an object.
Thank you for your time.
No comments:
Post a Comment