11 - ๐Ÿ†• "Classes"

Middleclass, lowerclass, upperclass... What do those mean? What is a class in a social regard?

What are we learning?

In this lesson we will:


ADTs are Limited

By definition, a simple ADT like the Stack we created last lesson is intended for single-use. If you need a collection of data and functions to be packaged into one named item, an ADT is your perfect choice.

๐Ÿค” But what if you needed more than one Stack for a more complex problem?

Playing Cards ๐Ÿƒ

A deck of cards is a great example of a Stack. You should, typically, only be able to select the card on top of the deck. But the deck needs 52 cards, each with a numeric value and a suit.ย 

If we use a simple ADT for a card, we would need to define a new ADT for each card in the deck - that's 52 ADT definitions.

What is a "Class"? ๐Ÿ“‘

The Oxford Dictionary defines a "class" as:

We can also define a Class as a blueprint - when you hear "sports car" you have a blueprint in your mind of the attributes of that type of car.

Class Diagram ๐Ÿ“ถ

Playing cards share attributes: suit (โ™ , โ™ฃ, โ™ฆ, โ™ฅ), and value. They might also be a "face card" or a special card called a "joker".

We can design a blueprint for this "Class" of item with a diagram - known as a class diagram (example on the right). Each property of a Playing Card object is listed as:
variable_name:type with an optional default value.

For now, ignore the + before each variable.

Declaring a Class in Code ๐Ÿ‘ฉโ€๐Ÿ’ป

Not every language can create objects but those that can require you to declare the blueprint of the object, similar to declaring a function.

The blueprint is called a class.
Instances of the class are called objects

// A blueprint of a Playing Card

class PlayingCard {

ย ย value;

ย ย name;

ย ย suit;

ย ย colour;

ย ย is_face = false;

}

"New" ๐Ÿ†•

To create instances of the object that is defined by the class definition we use the new keyword.

let card = new PlayingCard();

Then you can modify the properties of your instance:

card.suit = "Hearts";

card.value = 12;

card.name = "Queen";

card.is_face = true;

Those properties can be used and modified just like normal variables. We can also make as many cards as we want - perhaps putting them in an Array or Stack to make a deck!