Thursday, March 9, 2017

What is Encapsulation in Java and OOPS with Example

Encapsulation in Java or object-oriented programming language is a concept that enforces protecting variables, functions from outside of class, in order to better manage that piece of code and having the least impact or no impact on other parts of a program due to change in protected code. Encapsulation in Java is visible at different places and Java language itself provides many constructs 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 modifiers like protected or the public.

The true value of encapsulation is realized in an environment that 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 a change in requirement. Along with abstraction in java and polymorphism in Java, Encapsulation is a must know the 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 that make use of Encapsulation object-oriented concept. 

If you are looking for a quick guide on both OOPS and SOLID design principles in Java then you may find 10 Object-Oriented Design principles Java programmer should know interesting.

Btw, if you are new into the world of object-oriented programming and design then I also suggest you go through a hands-on course like UML and Object-Oriented Design Foundations by Karloy Neisztor on Udemy. It's a great course to understand the complete process of object-oriented analysis and design for creating quality software. 

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 creating an object in Java and constructors can accept an argument. 

Suppose we have a class Loan has a constructor and then in various classes, you have created an instance of the loan by using this constructor. now requirements change and you need to include the age of borrower as well while taking a 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 files 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 a change at one place? 

Yes, that is possible if we encapsulate Loan creation logic in one method say createLoan() and client code calling this method, and this method internally creates 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; = loan;
        this.borrower = borrower;
        this.salary = salary;
    //no argument constructor omitted here
   // create loan can encapsulate loan creation logic
    public Loan createLoan(String loanType){
     //processing based on loan type and then 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 the outside world to access these variables is better creating a getter and setters like the 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 a single channel of access for the 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 is a good choice in multi-threading
5. Encapsulation reduces the coupling of modules and increases cohesion inside a module because all pieces of one thing
is encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other parts of code.

What should you encapsulate in code

Anything which can be change and more likely to change in the near future is a candidate of Encapsulation. This also helps to write a more specific and cohesive code. An example of this is object creation code, code which can be improved in the future like sorting and searching logic.

Design Pattern based on Encapsulation in Java

Many design pattern in Java uses the encapsulation concept, one of them is Factory pattern which is used to create objects. Factory pattern is a better choice than a new operator for creating an object of those classes whose creation logic can vary and also for creating a different implementation of the same interface. 

The BorderFactory class of JDK is a good example of encapsulation in Java which creates different types of Border and encapsulates the creation logic of Border. Singleton pattern in Java also encapsulates how you create an instance by providing a getInstance() method. 

Since an object is created inside one class and not from any other place in code you can easily change how you create an object without
affect another part of the code.

Important points about 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 modifiers private, protected, and public.
4. Factory pattern, Singleton pattern in Java makes good use of Encapsulation.

Further Learning
SOLID Principles of Object-Oriented Design
Absolute Introduction to Object Oriented Programming in Java
Java - Object Oriented Programming [For Absolute Beginners]

Other Java design pattern articles you may like :


Anand Vijayakumar said...

Nice Explanation Javin. Clear & Crisp...

For my Take on Encapsulation - Click Here


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.


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...

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...


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();


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 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 ?

Anonymous said...

Dear Sir,What is the difference in creating a createloan method and using parameterized costructor,both ways we need to changw in all files where object is created...???????????????????

Unknown said...

Very good questions . Here are some 30 Java OOP concept interview questions, I have found immensely useful. Thanks

Unknown said...

Both are same

Anonymous said...

Your example description is a bit abstract please include some more points which are asked in questions above so that the readers wont have these kind of confusions in the future.

Post a Comment