Why should I use encapsulation if the code below will produce the same result?
The main benefit of encapsulation is the ability to mo
One way to use encapsulation is to hide implementation. Sometimes a getter, for example, isn't a getter. Consider a shape like a sphere, I wouldn't necessarily store the volume or surface area as a variable because I could calculate them at any time. I would still call the member functions getVolume and getSurfaceArea. The person who uses my code doesn't need to know if I calculate or simply store the value. By exposing my variables I lock them into a design decision that would have to change (or be broken) should I change my implementation. By hiding implementation you need only know the interface (not to be confused with Java's 'interface' ) It protects everybody that way and makes making future changes a much easier task.
It should be noted that there are times when setters/getter are not used and variables are exposed. Even in Java sometimes it just makes more sense not to hide instance variables.