In Java, encapsulation is one of the core concepts of Object Oriented Programming (OOP) in which we bind the data members and methods into a single unit. Encapsulation is used to hide the implementation part and show the functionality for better readability and usability. The following are important points about encapsulation.
Better Code Management:
We can change data representation and implementation any time without changing the other codes using it if we keep method parameters and return values the same. With encapsulation, we ensure that no other code would have access to implementation details and data members.
Simpler Parameter Passing:
When we pass an object to a method, everything (associated data members and methods are passed along). We do not have to pass individual members.
.
getter and setter:
getter (display the data) and setter method ( modify the data) are used to provide the functionality to access and modify the data, and the implementation of this method is hidden from the user. The user can use this method, but cannot access the data directly.
Example:
// Java program demonstrating Encapsulation
class Programmer {
private String name;
// Getter and Setter for name
// Getter method used to get the data
public String getName() { return name; }
// Setter method is used to set or modify the data
public void setName(String name) { this.name = name; }
}
public class Geeks {
public static void main(String[] args) {
Programmer p = new Programmer();
p.setName("Geek");
System.out.println("Name=> " + p.getName());
}
}
Output:
Name=> Geek
Top comments (0)