Java – Encapsulation

Encapsulation:

  • The concept of protecting the data with in the class itself.
  • We implement Encapsulation through POJO rules
  • POJO – Plain Old Java Object
  • Implementation rules: (POJO rules)
    • Class is Public (to make the object visible in communication).
    • Variables are Private (other objects cannot access the data directly).
    • Methods are public (to send and receive the data).

Defining get() and set() methods to Balance variable in Account class:

  • Set() : takes input value and set to instance variable.
  • Get() : returns the value of instance variable.
public class Bank
{
            private double balance;
            public void setBalance(double balance)
            {
                        this.balance = balance;
            }
            public double getBalance()
            {
                        return this.balance;
            }
}

Employee.java: (POJO class)

public class Employee
{
            private int num;
            private String name;
            private double salary;
            public void setNum(int num)
            {
                        this.num = num;
            }
            public int getNum()
            {
                        return this.num;
            }
            public void setName(String name)
            {
                        this.name = name;
            }
            public String getName()
            {
                        return this.name;
            }
            public void setSalary(double salary)
            {
                        this.salary = salary;
            }
            public double getSalary()
            {
                        return this.salary;
            }
}

AccessEmployee.java:

class AccessEmployee
{
            public static void main(String[] args)
            {
                        Employee e = new Employee();
                        e.setNum(101);
                        e.setName(“Amar”);
                        e.setSalary(35000);
                        System.out.println(“Emp Num : “+e.getNum());
                        System.out.println(“Emp Name : “+    e.getName());
                        System.out.println(“Emp Salary : “+e.getSalary());
            }
}
Scroll to Top