- Learning Java by Building Android Games
- John Horton
- 334字
- 2021-07-23 19:02:32
Remember that encapsulation thing?
So far we have seen what really only amounts to a kind of code-organizing convention; although we did discuss the wider goals of OOP. So now we will take things further and begin to see how we manage to achieve encapsulation with OOP.
Tip
Definition of encapsulation
Keeping the internal workings of your code safe from interference from the programs that use it while allowing only the variables and methods you choose, to be accessed. This means your code can always be updated, extended or improved without affecting the programs that uses it if the exposed parts are still made available in the same way. It also allows the code that uses your encapsulated code to be much simpler and easier to maintain because much of the complexity of the task is encapsulated in your code.
But didn't you say we don't have to know what is going on inside? So you might question what we have seen so far like this.
Note
Reasonable OOP student question: If we are constantly setting the instance variables like this rambo.health = 100;
, isn't it possible that eventually, things could start to go wrong, perhaps like this:
rambo.soldierType = "fluffy bunny";
This is a very real danger that encapsulation can prevent.
Encapsulation protects your class/objects of your class/code from being used in a way that it wasn't meant to be. By strictly controlling the way that your code is used it can only ever do what you want it to do and with value ranges that you can control.
It can't be forced into errors or crashes. Also, you are then free to make changes to the way your code works internally, without breaking any other games or the rest of your game, that might be written using an older version of the code.
weightlifter.legstrength = 100; weightlifter.armstrength = -100; weightlifter.liftHeavyWeight(); // one typo and weightlifter will rip off his arms
We can encapsulate our classes to avoid this and here is how.