Encapsulation in Java
Introduction
In this section, you will learn about Encapsulation in Java. Encapsulation is a process of wrapping code and data together into a single unit. It is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation In java
Encapsulation confirms that critical and sensitive
data is hidden from users. In order to achieve encapsulation, you must:
- Declare properties/ attributes as
private
. - Create a getter and setter to get and update the value of private variables.
Example:
package com.company;
public class BagWork {
public static void main(String[] args) {
Bag b1 = new Bag();
b1.setName("Allo Bag");
b1.setPrice(250);
System.out.println("Name is " + b1.getName());
System.out.println("Price is $" + b1.getPrice());
}
}
class Bag{
private String name;
private double price;
// Getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Advantages Of Encapsulation:
- Data hiding is possible.
- Increased security of data.
- Better Control of class properties and methods.
- Programmers can change one part of code without affecting other parts.
- Testing code becomes easy.