Game Development Reference
at soon, keep all your class's properties and methods private. It might not be entirely obvious to you
this early in your programming career, but (like wearing seatbelts in car) the weight of programming
experience says it's a good idea. When things do go wrong, they go very, very wrong, and you'll be
glad you did it.
Using private properties to lock down a class in this way is an aspect of object-oriented
programming called encapsulation . Encapsulation means that your class is com-
pletely sealed off from tampering by other classes and is as self-contained as possible.
If other classes want to access or modify any properties in an encapsulated class, they
have to follow very strict rules about doing so.
Using an underscore character to highlight private properties
Both of the Cen]bba class's private properties begin with an underscore character:
This is a naming convention that is entirely optional, but one that you'll be using in this topic. Preceding
the names of private variables with underscore characters helps you tell at a glance which properties
are private, which makes your code more readable.
When you start using getters and setters (more on them soon!), the underscore also
helps you distinguish between the private property and publicly accessible getter and
setter methods. By keeping the names exactly the same, with the exception of drop-
ping the underscore, you can create getter and setter methods that logically share the
same names as the private properties that they access or modify.
Communicating between classes using getters and setters
Classes often need to communicate with one another. But if all their methods and properties are pri-
vate, how can they do this? The trick is to create special public methods called getters and setters ,
which carefully negotiate communication between classes.
Let's create a scenario in which you have a bank full of money and a bank client who wants to access
that money. Let's start with an imaginary class called >]jg: