class Employee{
private int employeeId;
private String employeeName;
private String designation;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
How do we achieve encapsulation in Java?
We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters. Although a lesser degree of encapsulation can be achieved
by making the members public or protected.
What is encapsulation in object oriented programming?
Encapsulation
is an Object Oriented Programming
concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. ... C++ supports the properties of encapsulation
and data hiding through the creation of user-defined types, called classes.
Why Encapsulation use in Java Code?
Here are some advantages to use encapsulation in Java Code.
- Encapsulated Code is more flexible and easy to change with new requirements.
- By providing only getter and setter method access, you can make the class read only.
- Encapsulation in Java makes unit testing easy.
- A class can have total control over what is stored in its fields. Suppose you want to set the value of marks field i.e. marks should be positive value, than you can write the logic of positive value in setter method.
- Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environments.
- Encapsulation allows you to change one part of code without affecting other par
Benefits of encapsulation
- Provides abstraction between an object and its clients.
- Protects an object from unwanted access by clients.
- Example: A bank application forbids (restrict) a client to change an Account's balance.
Advantage of Encapsulation in java
- Objects encapsulate data and implementation details. To the outside world, an object is a black box that exhibits a certain behavior.
- The behavior of this object is what which is useful for the external world or other objects.
- An object exposes its behavior by means of public methods or functions.
- The set of functions an object exposes to other objects or external world acts as the interface of the object.
For indepth understanding of java click on