Encapsulation in Java

What is Encapsulation?

  • Packaging complex code or functions for ease of programming.
  • Putting all code in static main is not good programming. You need to break the code according to logic.
  • Encapsulation provides restriction over parts of code via public, private, & protected.
  • These parts of code would hide complex code.
  • A programmer skilled in particular area of Java can code that part and provide interface to use by other developers.
  • In regards of data, encapsulation may involve hiding of data.

 Example of Encapsulation in Real World

  • Take a washing machine. You need to be able to operate the washing machine.
  • If you were given knowledge of how circuit inside the machine worked or how the blades rotated, it would be difficult to get started.
  • So, encapsulated washing machine will only provide knowledge and usability of the functions required to make washing machine work.
  • This is done with the help of buttons, and manual about their usage.

Encapsulation in Java

  • Take the part of code and put it into its own class
public class WashingMachineButtons {      private Button _button;      private int _timer;            public void SetTimer(int TimerCount, Button _button) {          this._timer = TimerCount;          //.....      }            public void GetTimeLeft() {          //......      }  }
  • The logic for GetTimeLeft can be in different method too.
  • This reduces the code in main block.
  • This is Object Oriented Programming.

Advantages

  • Breaking functionality into small, maintainable units.
  • Grouping functions and data together.
  • Easier to fix bugs and test the application.
  • This makes unit testing possible where only specific class or methods are tested.