Encapsulation in Java

Encapsulation in Java is a mechanism of wrapping up the state (variables) and behavior (methods) together in one single unit (Class).

In Encapsulation, the variables of a class will be hidden from the other classes, and can only be accessed through the methods of the current class in which they are declared.

As in encapsulation, the data in a class is hidden from another class, so it is also known as data-hiding.

How can you achieve Encapsulation?

  • By defining the variables in a class as private. As private variables are not accessible outside the class, you can define getters and setters to read and write the values of these variables.
  • Getters and Setters are the standard names given to the methods which are used to read and write the values of private members.
  • Getters and Setters can make variable read-only or write-only.
  • Using getters and setters for the private variables also gives you an ability to protect variables from unauthorized access.

Consider the below example to understand the concept:

Let us create a class Employee which has two variables salary and the bonus of type int and a method to calculate salary and if you have defined them as public variables if someone gets unauthorized access to this variable from outside, they can easily modify the values (can put a negative value) which is not correct ( a salary cannot have a negative value)

Now if we define the variables as private then we will be using getters and setters method to read and write the values. To stop the unauthorized access and modification of data you have control in your setter method and can put all the necessary conditions.

See below code:

 package day2;

public class Employee {
	
	private int salary;
	private int bonus;
	
	void calculateSalary(){
		int totalSalary;
		
		totalSalary = salary + bonus;
		
		System.out.println("Total Salary "+ totalSalary);
	}

	//Getter to get the value of salary variable
	public int getSalary() {
		return salary;
	}

	//Setter to set the value of salary variable 
	//with a check of negative value
	public void setSalary(int salary) {
		if(salary<0){
			System.err.println("Invalid Salary");
		} else {
		this.salary = salary;
		}
	}

	//Getter to get the value of bonus variable
	public int getBonus() {
		return bonus;
	}

	//Setter to set the value of bonus variable 
	//with a check of negative value
	public void setBonus(int bonus) {
		if(bonus<0){
			System.err.println("Invalid bonus");
		} else {
		this.bonus = bonus;
		}
	}	
}


PS: For any questions, queries, or feedback. Feel free to write us at saurabh@qatechhub.com or support@qatechhub.com

Saurabh Dhingra

About the Author

Saurabh Dhingra

Follow Saurabh Dhingra: