Y12 Unit 0 - Class Structure
Y12 Unit 1 - Computational Thinking
Y12 Unit 2 - Networks
Y12 Unit 3 - OOP
Y12 Unit 4 - System Fundamentals
Abstract Data Structures (HL) Year 13 Unit

Encapsulation

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:

  • Prefix element – currently this can only be either 978 or 979. It is always 3 digits in length
  • Registration group element – this identifies the particular country, geographical region, or language area participating in the ISBN system. This element may be between 1 and 5 digits in length
  • Registrant element – this identifies the particular publisher or imprint. This may be up to 7 digits in length
  • Publication element – this identifies the particular edition and format of a specific title. This may be up to 6 digits in length
  • Check digit – this is always the final single digit that mathematically validates the rest of the number. It is calculated using a Modulus 10 system with alternate weights of 1 and 3.

Validation

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.

Advantages of Encapsulation

  • Data in a class can be made read or write-only
  • A class restricts the ways that its data and actions can be altered or called
  • A class can hide the way that data is stored
  • Easier to maintain, as changes to data and actions in a class, can take place without being apparent on the outside, as long as data and actions can still be accessed through the same way