The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation. You want to hide (mask) implementation details behind a public programming interface. By interface we mean the set of accessible methods your code makes available for other code to call, in other words, your codes API's. You can change the code without forcing a change in the code that calls your changed methods.
To provide maintainability, flexibility and extensibility you must encapsulate the code and to do this you
Set and Get methods | public class Football { public void setTeam(String t) { ... } Note: the only way to get to the instance variables is via the set and get methods |
When you create a new class that does something you will document only what access methods (get and set) are available to the public and this will not change, whoever implements your class can get updates and improved versions knowing that implementing this newer version will not break his/her program as the return types and passing variables to methods will be the same.
I have already covered access modifiers in the previous section creating and using methods, so I will cover the princples here, as we learned in the previous section Java provides two ways to hide class memembers
The objectives to hiding members is to protect from unintended changes, and secondly to protect consumers of the class from unintended consequences causing a minimum of disruption should the class need to change and as mentioned above we can use a special type of class called a bean to archive this.
To sum up encapsulation we have the following: