An object

In the real world, objects share two characteristics, that is, state and behavior. In other words, we can say that every object has a name, color, and more; these characteristics are simply the state of an object. Let's take the example of any type of pet: a dog and a cat will both have a name by which they called. So, in this way, my dog is named Ace and my cat is named Clementine. Similarly, dogs and cats have specific behaviors, for example, dogs barks and cats meow.

In the Explaining OOP section, we discussed that OOP is a programming model that is supposed to combine a state or structure (data) and the behavior (method) to deliver software functionality. In the previous example, the different states of pets make up the actual data, while the behavior of the pets is the method. 

An object stores the information (which is simply data) in attributes and discloses its behavior through methods.

In terms of an OOP language such as C#, an object is an instance of a class. In our previous example, the real-world object, Dog, would be an object of the PetAnimal class.

Objects can be concrete (that is, a real-world object, such as a dog or cat, or any type of file, such as physical file or a computer file) or they can be conceptual, such as database schemas or code blueprints.

The following code snippet shows how an object contains data and a method, and how you can use it:

namespace OOPExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("OOP example");
PetAnimal dog = new PetAnimal("Ace", PetColor.Black);
Console.WriteLine(dog.MyPet());
Console.ReadLine();
PetAnimal cat = new PetAnimal("Clementine", PetColor.Brown);
Console.WriteLine(cat.MyPet());
Console.ReadLine();
}
}
}

In the previous code snippet, we have created two objects: dog and cat. These objects are two different instances of a PetAnimal class. You can see that the fields or properties that contain data about the animal are given values using the constructor method. The constructor method is a special method used to create an instance of the class.

Let's visualize this example in the following diagram:

The preceding diagram is a pictorial representation of our previous code example, where we created two different Dog and Cat objects of the PetAnimal class. The diagram is relatively self-explanatory; it tells us that the object of Dog class is an instance of the PetAnimal class, as is the Cat object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.168.172