Friday, 17 May 2013

Java Encapsulation


Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
To run the example below, you need to set-up a new project in Eclipse and put both classes under this project. 

account class:
public class account {
private String name;
private String address;
private double balance;
public void setName (String n){
name=n;
}
public String getName(){
return name;
}
public void setAddress (String a){
address=a;
}
public String getAddress(){
return address;
}
public void setBalance(double g){
balance=g;
}
public double getBalance (){
return balance;
}

}
myaccount class

public class myAccount {
public static void main (String [] args){
account myAccount=new account();

myAccount.setName ("Tom");
myAccount.setAddress ("bugaosuni");
myAccount.setBalance (10000000);
System.out.println(myAccount.getName()+"\t"
+myAccount.getAddress()+"\t"
+myAccount.getBalance());
}

}


The addition of the word private in front of each of the account
class’s field declarations. The word private is a Java keyword. When a
field is declared private, no code outside of the class can make direct reference
to that field.

Instead of referencing myAccount.name, the useaccount program must
call method myAccount.setName or method myAccount.getName. These
methods, setName and getName, are called accessor methods, because they
provide access to the Account class’s name field.

Eclipse has a very nice function that can generate these for you so you don't have to type in all these tedious code. See screen capture below:








No comments:

Post a Comment