What Is Encapsulation In Java?

Many times when you will go to attend WebDriver Interview on 2+ years experience, Interviewer will ask you about Encapsulation. Best answer on Encapsulation In Java software development language Is as bellow.

Encapsulation
Encapsulation In Java software development language Is one of the OOP fundamental concept. It Is process of packing code and data together In to a single Unit. Best example Is capsule where powder of several medicines Is packed In single unit.

It Is also known as "data hiding" technique as fields of class are declared private and providing access to the fields via public methods. So anyone can not access private data fields directly outside the class. We can use setter and getter methods to get and set data In to It.

Advantages of Encapsulation
Few advantages of encapsulation.
  • It Increase the usability.
  • It promotes the easy maintenance in java software development.
  • It makes the class easy to use for clients.
  • Data access and modification control.
  • It Is easy to change one part of code without affecting other part of code.
Example of Encapsulation
Let's look at very simple example of encapsulation In java software development language . I have created encapsulation class Encaps.java as bellow.

Encaps.java
package oopbasics;

public class Encaps {

 private String name; 
 private int rollNo;
 
 //Data setter method
 public void setName(String newName) {
  name = newName;
 }

 //Data setter method
 public void setrollNo(int newrollNo) {
  rollNo = newrollNo;
 }

 //Data getter method
 public String getName() {
  return name;
 }

 //Data getter method
 public int getrollNo() {
  return rollNo;
 } 
}

In above class, I have created data setter and getter public methods to set and get data. All variables are declared as private to no one can access and modify them directly from outside the class.

Now we can set and get values from Encaps.java class as bellow.

Encaps.java
package oopbasics;

public class exeEncaps {

 public static void main(String[] args) {
  //Created object of Encaps class to set and get data.
  Encaps encaps = new Encaps();
  
  //Set data using setter methods of Encaps class.
  encaps.setName("Monika");
  encaps.setrollNo(56);
  
  //Get data using getter methods of Encaps class.
  System.out.println("RollNo : "+encaps.getrollNo()+", Name : "+encaps.getName());
 }
}

Output of above example Is as bellow.
RollNo : 56, Name : Monika

This Is the best explanation of encapsulation. You can find more links to read basic java software development tutorials on THIS PAGE.

1 comment: