Wednesday, March 9, 2016

java- Data encapsulation

Data encapsulation is the most important concept to grasp when programming with objects. In object-oriented programming data encapsulation is concerned with:
  • Combining data and how it's manipulated in one place. This is achieved through the state (the private fields) and the behaviors (the public methods) of an object.
  • Only allowing the state of an object to be accessed and modified through behaviors. The values contained within an object's state can then be strictly controlled.
  • Hiding the details of how the object works. The only part of the object that is accessible to the outside world is its behaviors. What happens inside those behaviors and how the state is stored is hidden from view.

Enforcing Data Encapsulation

Firstly, we must design our objects so that they have state and behaviors. We create private fields that hold the state and public methods that are the behaviors.
[blockquote shade="no"]For example, if we design a person object we can create private fields to store a person's first name, last name, and address. The values of these three fields combine to make the object's state. We could also create a method called displayPersonDetails to display the values of the first name, last name and address to the screen.
Next, we must make behaviors that access and modify the state of the object. This can be accomplished in three ways:
  • Constructor methods: A new instance of an object is created by calling a constructor method. Values can be passed to a constructor method to set the initial state of an object. There are two interesting things to note; one, Java does not insist that every object has a constructor method. If no method exists then the state of the object uses the default values of the private fields; two, more than one constructor method can exist. The methods will differ in terms of the values that are passed to them and how they set the initial state of the object.
  • Related Article  of JAVA

No comments:

Post a Comment