Home

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, February 26, 2015

Class & Instances

In Object Oriented world a class is a blueprint for the objects we want to create in code.

For example, let's say we wanted to represent a car in code. We can define a car using a C# class through attributes and behaviors. Some of the different attributes that make a car unique are its model, make, and color. For the car's behaviors, something a car does is start, so we can define this behavior. 


Putting this into code, we would have a car class with string attributes called model, make and color. We can also refer to these attributes as fields. This class would also have methods called start and stop because a car starts and stops. This is a behavior we want to define for the car. 


Car Class

string model;

string make;

string color;

start();

stop();


From the class blueprint, we can create several different types of cars. For example, one car could be a BMW 3 Series and have blue color. Another car might be a Merc Benz Class C and have green color. The way we create these individual cars from our car class blueprint is with the constructor. 


Now, both of these cars have a make, model, and color defined by the class blueprint, but the values of these attributes are different, depending on the car. Each of these cars can also start and stop so they would be able to call the start and stop method. This makes the Blue BMW car and the Green Merc car instances of the car class. 


These cars were constructed from the car class using a constructor, making them instances of the car class.