Codele / Advanced programming
Keeping data safe inside objects
A piggy bank does not let strangers reach in and grab coins. An object can guard its own data the same way: outsiders must ask, and the object checks the request.
- Encapsulation means an object keeps its data to itself and lets others use it only through methods that check the request.
- private means only the object’s own code may use it. public means anyone may.
- Without it, any line anywhere could set a balance to a silly value, and nothing would stop it.
- Java, C# and C++ refuse outside access when the program is translated. JavaScript uses a # in front of a name for real privacy.
- Python has no real privacy: a leading underscore asks people to keep out, and a double underscore only renames the data. Go hides lowercase names from other packages, not from the same package.
Loading the playable lesson…