Formal definition: Encapsulation refers to the inclusion of both data and actions into a single components. Classes contain data and actions that are built-in such a way so that their structure is hidden and can only be accessed outside the class via specific methods.
To put it in simple terms, you encapsulate information when you use the modifier private. We can related the class to being a capsule, a black-box, where people can’t access any of the inside data unless we allow them to.
Let’s take for example the Book class, which contains a variable called ISBN.
ISBN’s are 13 digit numbers that are calculated using a specific mathematical formula and include a check digit to validate the number.
Each ISBN consists of 5 elements with each section being separated by spaces or hyphens. Three of the five elements may be of varying length:
If the ISBN variable was public, then we could set it to anything, even an invalid ISBN. I could possibly just set it to “Edwin Lagos”, which is obviously not an actual ISBN number. Having a modifier method would allow us to create some sort of validation.
public void setISBN(String newISBN) { if(newISBN first three characters are not 978 or 979) { throw new ISBNException("this is not a valid ISBN); } other checks for valid ISBN... // if ISBN passes all checks this.ISBN = newISBN }
Because we have encapsulated our data using private and we use modifier methods with validation, we are sure to find a valid ISBN in this class.