Monday, 30 January 2017

ENCAPSULATION IN JAVA

The process of creating a class by hiding internal data from the outside world and accessing it only through public exposed method is known as data encapsulation / data hiding.

To develop encapsulation in java
  • ·        By declaring variables as private, to restrict it from direct access and
  • ·     By defining one pair of public setter and getter methods to access private variables. 

Example –
class Account{
private double balance;
          public double getBalance() {
                   return balance;
          }
          public void setBalance(double balance) {
                   this.balance = balance;
          }
}
public class Test1 {
          public static void main(String[] args) {
                   Account a = new Account();
                   a.setBalance(50000);
                   System.out.println(a.getBalance());
          }
}

Output –

50000.0

No comments:

Post a Comment