We just saw how breaking a long program up into small functions helped to make it easier to read and understand. It also helped to eliminate a lot of duplicated code. But we can do even better than that.
By collecting functions that operate together on the same data and putting them into one neat bundle, we can organize our program even more. We call these bundles of functions and data a class.
Here is what our SOS program looks like when wrapped in a class.
The first new thing is the name of the class:
... lots of code here...
The class is named Morse. But way down at the end of the class, we have what is called an instance of the class Morse (that's the object_morse part). We call instances of classes objects.The class is like a dictionary definition of the code. An instance of a class is a chunk of memory that may contain actual data. There would be only one class Morse, but you could have a number of objects of the class Morse.
Classes and objects are especially nice when programs get longer. By containing code in neat little packages, we can avoid problems that happen when we might want to take some code someone else wrote, and put it into our own program. That person may have used the word dot or dash for something else already. The computer would see his function and also our own, and would not know which to use.
When the function is wrapped in a class, the computer knows which function to use, even if they have the same name, because we tell it which object it is in. Here is the line in our new program that does that:
We will get a lot of practice with classes and objects, and all of this will become second nature in no time at all.
There is one more new concept in this program. Notice the line that says
just before the dot() function? In a class, all the names are private unless you deliberately make them public. Private names can only be used inside the class. Public names can be used by code that is outside of the class.
In our case, I made all of the functions in the class public. But since this program actually only uses send_SOS() from outside the class, I could have put the public declaration just before send_SOS(), and thus kept all of the other functions in Morse private. Keeping things private is a good way to prevent someone from accidentally using a function we don't want them using by itself. We might want to give them all the letters of the alphabet, but keep dot() and dash() private, so that only valid Morse code would ever be sent.
I have been calling our bits of code functions. But once they are inside a class, we call them methods. So send_SOS() and dot() and dash() are all methods in the class Morse. They used to be functions, but now they are in a class, we call them methods.