Encapsulation in Java Explained with Example

Encapsulation in Java

The term encapsulation means to enclose in a capsule, or to wrap something around an object to cover it. In object-oriented programming, encapsulation covers, or wraps, the internal working of a Java object.

  • Data variables , or fields , are hidden from the user of the object.
  • Methods, the functions in Java, provide on explicit service to the user of the object but hide the implementation.
  • As long as the services do not change, the implementation can be modified without impacting the user.
Example:
An analogy for encapsulation is the steering wheel of a car. When you drive a car whether it is your car , a friend's car, or a rental car, you probably never worry about how the steering wheel implements a right-turn or left-turn function. The steering wheel could be connected to the front wheels in a number of ways: ball and socket, rack and pinion, or some exotic set of servo mechanisms.

As long as the car steers probably when you turn the wheel, the steering wheel encapsulates the functions you need-you do not have to think about the implementation.


Encapsulation:Example



A Simple Model

Suppose you are asked to create a model of a typically employee. What data you might want to represent in an object that describes an employee?

  • Employee ID: You can use as the unique identifier for the employee.
  • Name: Humanizing an employee is always a good idea!.
  • Social Security Number: For US employee only. You may want some other identification for non-U.S employees.
  • Salary: How much the employee makes is always good to record.
What operations might you allow on the employee object?

  • Change Name: If the employee gets married or divorced , there could be a name change.
  • Raise Salary: Increases based on merit.

After an employee object is created, you probably do not want to allow changes tot the Employee ID or Social Security fields. Therefore, you need a way  to create an employee without alterations expect through the allowed methods.

Encapsulation: Private Data, Public Methods 

One way to hide implementation details is to declare all of the fields private.



In this example, the fields custID name, and amount, are now marked private, making them invisible outside of the methods in the class itself.

For example:

CheckingAccount  ca = new CheckingAccount():

ca.amount = 1_000_000_000.00  // illegal !


About Codingwelove

Codingwelove
Recommended Posts × +

0 comments:

Post a Comment