Java Encapsulation - The Coding Shala

Home >> Learn Java >> Java Encapsulation

Java Encapsulation

Java Encapsulation is a process of wrapping code and data together into a single unit. We can say Encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield, for example, a capsule. In encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of its own class so it is also known as data-hiding. 
Java Encapsulation - The Coding Shala
We can achieve Java Encapsulation by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. These public methods called getter and setter methods. Using these getter and setter we can make our class read-only or write-only. Using Encapsulation we can control the data. The encapsulation class is easy to test.

The Java Bean class is the example of a fully encapsulated class.

Example of Java Encapsulation

The following example explains Java Encapsulation: 

//Java Encapsulation Example
//thecodingshala.com

class Student{
 private int id;
 private String Name;
 private String DeptName;  //private data
 //these are getter and setters
 public int getId() {  //getter
  return id;
 }
 public void setId(int id) { //setter
  this.id = id;
 }
 public String getName() {
  return Name;
 }
 public void setName(String name) {
  Name = name;
 }
 public String getDeptName() {
  return DeptName;
 }
 public void setDeptName(String deptName) {
  DeptName = deptName;
 }
}

class Main{
 public static void main(String[] args) {
  Student s1 = new Student();
  s1.setId(1);
  s1.setName("Akshay saini");
  s1.setDeptName("Computer Engineering");
  
  System.out.println("Student information below:");
  System.out.println("Student id is: "+s1.getId());
  System.out.println("Student Name is: "+s1.getName());
  System.out.println("Student Department is: "+s1.getDeptName());
  
 }
}
Output: 

Student information below:
Student id is: 1
Student Name is: Akshay saini
Student Department is: Computer Engineering



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala