Encapsulation In Java

Encapsulation -Want or Do not Want

Encapsulation in java is a process of wrapping code and data together into a single unit We can create a fully encapsulated class in java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

Advantage of Encapsulation

By providing only setter or getter method, you can make the class read-only or write-only.

It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 500 only, you can write the logic inside the setter method.

Interview Tips Encapsulation in Java and OOPS

  1. Encapsulation in Java allows you to control that it's object can access data members
  2. Encapsulated Code is more flexible and easy to change with new requirements.
  3. Encapsulation in Java makes unit testing easy.
  4. Encapsulation also helps to write immutable class which are a good choice in multi-threading environment.
  5. Encapsulation reduce coupling of modules and increase cohension inside a module because all piece of one thing are encapsulated in one place.
  6. Encapsulation allows you to change one part of code without affecting other part of code.
  7. A class can have total control over what is stored in it's fields. You can write logic with setter method like age must be positive
  8. Encapsulated Code is more flexible and easy to change with new requirements.
  9. Singleton pattern in Java makes good use of Encapsulation.

Example of encapsulation in java

package com.javatportal;

public class Student {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name){ 
 	this.name=name 
 	}}
 	
 	
 package com.javatportal;

public class Student {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name){ 
 	this.name=name 

 	}
}
Compile By: javac -d . Test.java
 Run By: java com.javatportal.Test