Encapsulation

Encapsulation is used for protecting the data from the other users accessing the respective class, by marking it as private. The required encapsulated data can be retrieved by using the Java getter and setter methods.

An example of a Java program using encapsulation

The following is an example of encapsulation in a Java program:

package MyFirstPackage;

class encap {
  private int salary ;

  public int getI() {
    return salary;
  }

  public void setI(int i) {
    // encap thiExmp = new encap();
    // thiExmp.salary = i * 10;

    this.salary = i * 10;
  }
}

public class encapsulation {
  public static void main(String[] args) {
    encap vara = new encap();
    vara.setI(10);
    System.out.println(vara.getI());
  }
}

The output for the preceding code is as follows:

100

Get Learning Selenium Testing Tools - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.