top of page

Subscribe to Wisdom

Thanks for Subscribing!

Writer's picturePuru Uttam

Encapsulation in Java

As a name suggests, encapsulation of data i.e. wrapping up of data into a single unit.

  • It is a mechanism under which data and code bind together to achieve data-hiding as it makes the limited access of the data outside of it's scope.

  • It is an important feature of OOPs (Object Oriented programming).

  • It prevents outer classes from accessing and manipulating fields and methods of a class as it can make the class read-only or write-only which means setters or getters methods can be skipped .


setSalary(int salary)  // provides write-only access
getSalary() // provides read-only access

  • It is also known as a combination of abstraction and data-hiding as class is exposed to the user without providing any implementation details.

  • It is used to achieve reusability as it is easy to change with new requirements.

  • It helps to control the values of our data fields.


//Example
class Employee {
  private int salary;

  public void setSalary(int salary) {
    if (salary >= 1000) {
      this.salary = salary;
    }
  }
}

  • With the help of access modifiers we can control the access of data members and member functions.


 class Employee{

  public int id;
  private int salary;

  //Parameterized constructor
  Employee(int id, int salary) {
    this.id = id;
    this.salary = salary;
  }
  
  // Setters
 public void setId(int id) {
    this.  id = id;
  }
 public void setSalary(int salary) {
    this.salary = salary;
  }
  
  // Getters
  public int getId() {
    return id;
  }
  public int getSalary() {
    return salary;
  }
}

class EmployeeMain {
  public static void main(String... args) {

    Employee employee = new Employee();

    employee.setId(1);
    employee.setSalary(10000);

    // access age using getter
    System.out.println("Employee 1 salary is " + employee.getSalary());
  }
}

If we try to access the salary field from EmployeeMain class, we will get error as it is private.

// error: salary has private access in Employee
employee.salary = 10000;
7 views0 comments

Recent Posts

See All

Commentaires


Modern Digital Watch
bottom of page