What is Encapsulation in Java?

Encapsulation is a mechanism of binding code and data together in a single unit. Let’s take an example of Capsule. Different powdered or liquid medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class.


However if we setup public getter and setter methods to update (for example void setAge(int age))and read (for example  int getAge()) the private data fields then the outside class can access those private data fields via public methods.
This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better.
Example of Encapsulation:
/* Create a class Encapsulation.java */
public class Encapsulation {
   private String name;
   private int age;

   public int getAge() {
      return age;
   }

   public String getName() {
      return name;
   }

   public void setAge( int newAge) {
      age = newAge;
   }

   public void setName(String newName) {
      name = newName;
   }
}

File TestEncap.java
public class TestEncap {

   public static void main(String args[]) {
      Encapsulation encap = new Encapsulation();
      encap.setName("Vinni");
      encap.setAge(25);

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
   }
}

Output

Name : Vinni Age : 25

Click here to find complete Java Tutorials Series
Java Inheritance   << Previous     ||     Next >>   Java Abstraction

Popular posts from this blog

18 Demo Websites for Selenium Automation Practice in 2026

Mastering Selenium Practice: Automating Web Tables with Demo Examples

14+ Best Selenium Practice Exercises to Master Automation Testing (with Code & Challenges)

Selenium Automation for E-commerce Websites: End-to-End Testing Scenarios

Selenium IDE Tutorial: A Beginner's Guide to No-Code Automation Testing

A Complete Software Testing Tutorial: The Importance, Process, Tools, and Learning Resources

Top 10 Highly Paid Indian-Origin CEOs in the USA

Java Regular Expressions: A Comprehensive Guide with Examples and Best Practices

Artificial Intelligence in Self-Driving Cars: Navigating the Future of Transportation

AI and Data Privacy: Risks, Regulations & How to Use AI Safely in 2026