Comp 101 Classes and Objects: Overview

Classes and Objects

Classes and objects are some of the most essential building blocks of programming! They allow us to do object oriented programming - one of the most common and useful programming styles.

We can think of classes as blueprints - they tell us what are the essential parts of a given object. While objects are the actual manifestation of that blueprint.

Let's look at an example. Say we're a developer building a neighborhood - we want a blueprint so we know what are the essential parts of a house.

class House {
     style: string = "";
     color: string = "";
     bedrooms: number = 0;
     frontPorch: boolean = false;
}

The House class tells us the essential elements of a House - all houses will have a style, color, bedrooms, and the option of a front Porch - we call these properties.

Now that we have our blueprint lets build some houses!

1   let jeffreysDreamHouse = new House();
2   print("Color: " + jeffreyDreamHouse.color); //Prints "Color: "
3   jeffreysDreamHouse.style = "Craftsman";
4   jeffreysDreamHouse.color = "Carolina Blue";
5   jeffreysDreamHouse.bedrooms = 101;
6   jeffreysDreamHouse.frontPorch = true;
7
8   let kitsDreamHouse = new House();
9   print("Color: " + kitsDreamHouse.color); //Prints "Color: "
10 kitsDreamHouse.style = "Fortress";
11 kitsDreamHouse.color = "Black";
12 kitsDreamHouse.bedrooms = 1;
13
14 print("Jeffrey's dream house is " + jeffreysDreamHouse.color + " and has " + jeffreysDreamHouse.bedrooms + " bedrooms.");
15 //Prints "Jeffrey's dream house is Caroliona Blue and has 101 bedrooms."
16 print("Kit's dream house is a " + kitsDreamHouse.style);
17 //Prints "Kit's dream house is a Fortress"

Notice to create a new house object we have to use the new keyword followed by className().

Notice on lines 2 and 9 when we try to print the color of each house only a blank string is printed. This is because in our class we set the default value of color to an empty string. After we've updated these properties by accessing them using the dot operator the updated properties are printed on lines 15 and 17.

Does updating all those properties seem like a whole lot of work? Check out our page on constructors which helps streamline this process!