Start Coding Now

Encapsulation in Java - Data Hiding

Learn about encapsulation in Java. How to wrap code and data together into a single unit using private fields and public methods.

Encapsulation

Encapsulation is the process of wrapping code and data together into a single unit.

How to achieve:

  • Declare variables of a class as private.
  • Provide public setter and getter methods to modify and view the variables values.
  • public class Person {
      private String name; // restricted access

    // Getter public String getName() { return name; }

    // Setter public void setName(String newName) { this.name = newName; } }

    Frequently Asked Questions