Monday, 23 December 2013

Show Encapsulation by hiding data!!

One of the most important feature in Java is Encapsulation. Here I am going to brief about encapsulation.Hope it will be useful for you.Don't come into the conclusion only with this blog.Dig other site also to get more information about encapsulation.

There will be some situations where we required to show only some information not all.How can we implement that ? For example,Its enough to show overall attendance percentage to students. But when it comes faculty, all details need to be displayed.Here students will be the class and Faculty will be the class. Attendance here is the data. What we are doing here is we are protecting and hiding data from student class.How can we acheive this? The solution for this question is Encapsulation. Encapsulation is about to protect the data(varaibles), information(methods) etc.By using access modifiers such as public, protect, default and private we can implement encapsulation.

Encapsulation is also for protect information which are prone to change. Encapsulation is used to maintain code just in one place. not scattered around code is easy to change.This can be better explained with an example.There a class called loan and it has a parametrized constructor.Other class have an instance using this constructor. Now requirements have changed to add another parameter in constructor. So you need to change everywhere you are calling this constructor. This is what code is scattered and encapsulation can handle it by access specifier.

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;
}

}



No comments:

Post a Comment