Encapsulation
Encapsulation is one of the key concepts of Object-oriented programming. Encapsulation keeps data safe from outside interference and misuse of data. Encapsulation binds code and data together. Data inside a class must only be accessible by methods defined inside the same class.
- Encapsulation binds the code and the data together.
- Encapsulation keeps the data both safe from outside interferences and misuse.
- The basis of encapsulation in java is “CLASS”.
- The “OBJECTS” are instances of the class.
- The Class “DOES” encapsulate the complexity of implementation inside.
- The mechanism of hiding this complexity is known as “ENCAPSULATION”.
- Encapsulation is “hiding details at the level of implementation”.
- The abstraction is “Exposing the interface of the class to external world”.
- Access specifier “private” is used to encapsulate or hide the implementation from the external world.
- Access specifier “public” is used to expose the functions or interface to the external world.
![]() |
Encapsulation |
In simple words, all the private data and methods in a class can be only accessed by using public methods defined in that class to the outside world.
Benefits of Encapsulation
- Data security and better access control
- Low coupling
- Code reuse
- Better testing
Encapsulation Example(An encapsulated class)
class Product{
private int product_id;//make all the data fields private
first
private String product_name;
private float product_price;
private float product_tax;
private float product_service_charge;
// create get/set methods for each data member
//you can also
create class constructor
public int getProduct_id() {
return product_id;
}
public Product(int product_id, String product_name, float product_price, float product_tax,
float product_service_charge) {
super();
this.product_id = product_id;
this.product_name = product_name;
this.product_price = product_price;
this.product_tax = product_tax;
this.product_service_charge = product_service_charge;
}
public Product() {
super();
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public float getProduct_price() {
return product_price;
}
public void setProduct_price(float product_price) {
this.product_price = product_price;
}
public float getProduct_tax() {
return product_tax;
}
public void setProduct_tax(float product_tax) {
this.product_tax = product_tax;
}
public float getProduct_service_charge() {
return product_service_charge;
}
public void setProduct_service_charge(float product_service_charge) {
this.product_service_charge = product_service_charge;
}
}
public class EnacapsulationDemo {
public static void main(String[] args) {
Product p1=new Product();
p1.setProduct_id(15);
// set the value by setter method
System.out.println(p1.getProduct_id());
// get
the value by getter method
}
}