WEEK: 15

Classes

There are two vital questions we must answer whenever we look at new things. What is it? And Why do we need it?

Now, remember, a class is a blueprint or template for an object. That is the proper definition.

Classes contain properties and functions.

Properties are what describe the class and the functions are what the class can do.

That might not make a lot of sense yet, but let’s think of an example.

Let’s say we have a Dog class. How can we describe a dog (any dog)?

They have an eye color, hair color, a weight, a name and a breed. There are more things, but this is pretty good list.

What can Dogs do? They can eat, sleep (a lot), drink, run, play, bark, sniff and more.

So, this could be a template for any dog really. So, what might this look like in code? In p5.js it looks like this with just its properties:

Notice it starts with the keyword class then the name of the class and then the class opens with a { and then at the end of the class it closes with }.

class Dog {
  constructor(name, breed, weight, eyeColor, hairColor ) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.eyeColor = eyeColor;
    this.hairColor = hairColor;
  }
}

What is this. This keyword refers to the class variable. While the variable without the this. is the variable being passed in. The constructor is a keyword saying that it will create the object. (i.e. We use the constructor to create the specific dog)

What about if we add the functions in?

class Dog {
  constructor(name, breed, weight, eyeColor, hairColor ) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.eyeColor = eyeColor;
    this.hairColor = hairColor;
  }

  eat()
  {
    text(this.name + "is eating...", 100, 100);
  }

  sleep()
  {
    text(this.name + " is sleeping...", 200, 200);
  }
}

Notice in a class, the function keyword does not precede the function definitions. In classes, the functions are known because they end with parentheses. In the case of eat and sleep, nothing is sent in, but there are times when we can send parameters in. (For example, the constructor is a function and it takes in parameters).

And again, why do we use classes?

The answer is simple. We want to increase our reusability of our code and reduce the maintenance. That is sole goal whenever we write code. Think about a program that requires a lot of variables. I imagine you have one in mind right now. Imagine if we reduce those into just a few variables. That would be a good thing.

Okay let’s go onto objects.


Previous section:
Next section: