Friday, March 9, 2012

What is Encapsulation in Java and OOPS with Example

Encapsulation in Java or object oriented programming language is a concept which enforce protecting variables, functions from outside of class, in order to better manage that piece of code and having least impact or no impact on other parts of program duec to change in protected code. Encapsulation in Java is visible at different places and Java language itself provide many construct to encapsulate members. You can completely encapsulate a member be it a variable or method in Java by using private keyword and you can even achieve a lesser degree of encapsulation in Java by using other access modifier like protected or public. true value of encapsulation is realized in an environment which is prone to change a lot and we know that in software requirements changes every day at that time if you have your code well encapsulated you can better manage risk with change in requirement. Along with abstaction in java and polymorphism in Java, Encapsulation is a must know concept. In this java tutorial  we will see How to use encapsulation in Java, advantage and disadvantage of Encapsulation and various design patterns and real life problems which makes use of Encapsulation object oriented concept. If you are looking for a quick guide on both OOPS and SOLID design principle in Java than you may find 10 Object Oriented Design principles Java programmer should know  interesting.

What is Encapsulation in Java

Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. this can be better explained with a simple example of encapsulation in Java. we all know that constructor is used to create object in Java and constructor can accept argument. Suppose we have a class Loan has a constructor and than in various classes you have created instance of loan by using this constructor. now requirements change and you need to include age of borrower as well while taking loan. Since this code is not well encapsulated i.e. not confined in one place you need to change everywhere you are calling this constructor i.e. for one change you need to modify several file instead of just one file which is more error prone and tedious, though it can be done with refactoring feature of advanced IDE wouldn't it be better if you only need to make change at one place ? Yes that is possible if we encapsulate Loan creation logic in one method say createLoan() and client code call this method and this method internally crate Loan object. in this case you only need to modify this method instead of all client code.

Example of Encapsulation in Java

class Loan{
    private int duration;  //private variables examples of encapsulation
    private String loan;
    private String borrower;
    private String salary;
   
    //public constructor can break encapsulation instead use factory method
    private Loan(int duration, String loan, String borrower, String salary){
        this.duration = duration;
        this.loan = loan;
        this.borrower = borrower;
        this.salary = salary;
    }
   
    //no argument consustructor omitted here
    
   // create loan can encapsulate loan creation logic
    public Loan createLoan(String loanType){
  
     //processing based on loan type and than returning loan object
      return loan;
    }
  
}

In this same example of Encapsulation in Java you see all member variables are made private so they are well encapsulated you can only change or access this variable directly inside this class. if you want to allow outside world to access these variables is better creating a getter and setter e.g. getLoan() that allows you to do any kind of validation, security check before return loan so it gives you complete control of whatever you want to do and single channel of access for client which is controlled and managed.

Advantage of Encapsulation in Java and OOPS

Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:

1. Encapsulated Code is more flexible and easy to change with new requirements.
2. Encapsulation in Java makes unit testing easy.
3. Encapsulation in Java allows you to control who can access what.
4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading
environment.
5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing
are encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other part of code.

What should you encapsulate in code
Anything which can be change and more likely to change in near future is candidate of Encapsulation. This also helps to write more specific and cohesive code. Example of this is object creation code, code which can be improved in future like sorting and searching logic.

Design Pattern based on Encapsulation in Java

Many design pattern in Java uses encapsulation concept, one of them is Factory pattern which is used to create objects. Factory pattern is better choice than new operator for creating object of those classes whose creation logic can vary and also for creating different implementation of same interface. BorderFactory class of JDK is a good example of encapsulation in Java which creates different types of Border and encapsulate creation logic of Border. Singleton pattern in Java also encapsulate how you create instance by providing getInstance() method. since object
is created inside one class and not from any other place in code you can easily change how you create object without
affect other part of code.

Important points aboue encapsulation in Java.

1. "Whatever changes encapsulate it" is a famous design principle.
2. Encapsulation helps in loose coupling and high cohesion of code.
3. Encapsulation in Java is achieved using access modifier private, protected and public.
4. Factory pattern , Singleton pattern in Java makes good use of Encapsulation.

Other Java design pattern articles you may like :

12 comments :

Anand VijayaKumar said...

Nice Explanation Javin. Clear & Crisp...

For my Take on Encapsulation - Click Here

Anand

Anonymous said...

Very well said.
In short, from OOAD perspective:
- Abstraction is about 'What' a class can do.
- Encapsulation is more about 'How' to achieve that functionality.

Since it is not required to reveal the information of 'How'(trade/business secrets) the class achieves a functionality - hence we wrap it with private and protected scope based on need.

-Pankaj

Javin @ set path in java said...

well said Pankaj, It will help to understand difference between Abstraction and Encapsulation

Anonymous said...

Does Data hiding and Encapsulation is same principle ? Some one ask me in OOPS Interview that What is data hiding and What is Encapsulation, I am getting confused is it two different concept or just one ?

Rashmi said...

Thanks for sharing. I would like to share few OOPS Interview questions which is based on concept of Encapsulation, Abstraction and Polymorphism in Java programming.

What is difference between Encapsulation and Abstraction in Java or OOPS ?

What is difference between Encapsulation vs Data hiding in Java?

Encapsulation vs Abstraction vs Data hiding vs Polymorphism

Difference between Encapsulation and Inheritnace in Java.

Encapsulation vs Inheritance vs Composition in Java

Can you give a real life Example of Encapsulation in Java which you have used in your Java project ?

how do make method and field encapsulated in Java programming language ?

Anonymous said...

honestly i don't get it,how we can create object in this example
consructor of class Loan has private modificator
we need static method that return new Loan(....)

Javin @ xml interview questions said...

@Anonymous, you are correct. Actually createLoan() was that static factory method which supposed to return Loan object, until now, when I realized it's missing static modifier :). Thanks for pointing it out.

Anonymous said...

Hello,
I am unable to get the differences between Object initialization through Parameterized constructor and the creatLoan() method from the explanation above. Both are doing the same job..

Suppose, If we want to add a new attribute to the class in future (borrower age as per the example), Its necessary to modify all the object creation codes in all the files. But how come this effort will be reduced in case of the creator methods?? (Because we are introducing an extra attribute in the class, we need it through some mechanism from the users(object creation requestor files). And that will ofcourse require extra modifications in files.,

Can you please clarify this...

Thanks.

Anonymous said...

(continuation of comment logged:June 11, 2013 at 1:45 AM )

For Example :

Code At Present:

Loanacc l = new Loanacc(ATT1,ATT2,ATT3); // Obj creation using parameterized constructors

Loanacc l = new Loanacc();

l.createLoan(ATT1,ATT2,ATT3); // obj creation using create() method


To add AGE in future, the above lines may be changed to,

Loanacc l = new Loanacc(ATT1,ATT2,ATT3,AGE);

Loanacc l = new Loanacc();

l.createLoan(ATT1,ATT2,ATT3,AGE);

So, this requires code change in all the files whichever has the above object creation code(no matter which method is used)..,

Am I missing some understanding here?

Anonymous said...

OOP is meant to be a programmer own secret jutsu, the stronger your jutsu is the easier you can defeat "Work" :-)

class Loanacc{

function createLoan($ATT1 = null ,$ATT2 = null,$ATT3 = null,$AGE = null){

echo "Hi i am " . $ATT1 " and my age is " . $AGE;
}
}


Loanaccl = new Loanacc()

Loanaccl->createLoan(firstname,middlename,lasname,15); // should output "Hi i am firstname and my age is 15

Anonymous said...

if we have public getter and setter then those variables becomes public ...so wats d use??

Anonymous said...

Gone through above loan creation example. My question is do we need to pass relevant parameters to createLoan method

ex : createLoan(int duration, String loan, String borrower, String salary) . if we not providing above parameter how can we create loan object dynamically. Then how can code flexibility happen, everywhere in application where createLoan method has no change ?

Post a Comment