Java Tutorial 3: Introduction to object oriented programming Encapsulation

In the Last Tutorial we discussed the concept of Inheritance. Today we are gonna touch another important concept called Encapsulation. I will start of by introducing the formal definition of Encapsulation as  found here. Encapsulation is a way by which data and functions are combined into one structure or entity and treated as one. In older approaches of programming data and functions were kept independent of each other. This created problems for the programmers. As the size of the program grew so did its complexity. By combining the two into one entity programmers's job simplified :-



  • Programmers were able to control the visibility of data across various entities in a manner.
  • The internal representation of object is hidden from outside the class. This is beneficial because in this way it prevents the users from setting the internal data of the component into an invalid or inconsistent state. 
Encapsulation is most often compared to a capsule which not only encloses its contents, but also protects it from the exterior environment.



Encapsulation in java is achieved at two levels by controlling access class and its data members:
  • Top level: Here we control the access to the class itself. If we attach the modifier public to a class it is visible to everyone. If no modifier is attached the class is only visible within its Package(Will discuss this in tutorials to come).
  • Member level: Here we control the access to all the members of the class(both data and methods). The members can have one of the four access levels- default(Where no specifier is mentioned), public, private and protected. An excellent explanation about the four specifiers is available on here.
    • Default :Visible to the package
    • Private :Visible to the class only.
    • Public : Visible to the world.
    • Protected: Visible to the package and all subclasses.



0 comments: