Monday, April 28, 2014

Object Oriented Programming - Encapsulation

Encapsulation in Object Oriented Programming is a concept in which it enforces protecting attributes and behavior by wrapping inside a single unit(a class in Java) and restricting accessing to the inner workings of the objects based on that class.The true power of encapsulation is that the changes done to our protected code will result in bare minimal changes or no change to other parts of the application.

In principle the object shouldn't reveal any thing about it's inner workings and provides only things that are necessary for other parts of the application to work.

We can do this in Java by completely encapsulate a member variable or member function by declaring them as private or you can encapsulate partially by declaring them protected.

Let me give an example

Lets say we have a BankAccount class and we don't want other parts of the program reach in my balance and change it without going through the usual withdraw() or deposit() methods.This will cause a havoc in my program.

You may ask, we are allowing to change the balance through the deposit and withdraw methods.Yes.But how can my balance updated without doing any withdraw or deposit operations.In these two methods we may be doing other things like auditing or logging, without this functionality we might not know what's happened if some thing goes wrong(like who done the transfer and how much amount or who authorized the transaction etc).

To secure the data we should declare those attributes as private.We are not secretive here we are reducing the dependencies in other parts of the program.So any changes done in my program won't affect other parts of the application.

package com.ramesh.domain;  
 import java.util.Date;  
 public class BankAccount {  
      private String accountId;  
      private long balance;  
      private String accountType;  
      private Date dateOpened;  
      public void withdraw() {  
           System.out.println("Inside withdraw");  
      public void deposit() {  
           System.out.println("Inside deposit");  
      // setters and getters  


1) Easy to change our code with new requirements without affecting other parts of the program.
2) Easy for unit testing.
3) Let us control who can access what.

That's all about Encapsulation...Thanks for reading !!!!!

No comments:

Post a Comment