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:
Realize that ADT's are good for one-off custom data types
How do we make several different instances of an ADT?
Discuss the definition of a "class"
See our first Class diagram
Start discussing Object-Oriented Programming (OOP)
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:
"a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality."
"assign or regard as belonging to a particular category."
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!