Java Encapsulation

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 */
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;

public class TestEncap {

   public static void main(String args[]) {
      Encapsulation encap = new Encapsulation();

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


Name : Vinni Age : 25

Java Inheritance   << Previous     ||     Next >>   Java Abstraction

Click here to find complete Java Tutorials Series

Subscribe FB Group Techlistic on FB
Join Telegram channel at
Feel free to ask queries or share your thoughts in comments or email me.


Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

Selenium WebDriver - Take Screenshot and Partial Screenshot Commands

Top 25 Must to know Selenium Webdriver Commands List

Selenium Essentials - How to become expert in Automation Testing?

Selenium WebDriver - Browser and Navigation Commands