Menu

1 / 2

Encapsulation in Java

DEV Community·Mohamed Ajmal·6 months ago
#FlwopI5V
#development#webdev#java#frontend#name
Reading 0:00
15s threshold

Encapsulation in Java is the process of wrapping data (variables) and the code that acts on that data (methods) together as a single unit, typically a class.

Encapsulation in Java is achieved using:

Private data members,

Public getter and setter methods.

Benefits:

Data Control: You can make a class read-only (by providing only getters) or write-only (by providing only setters).

Validation: Setters allow you to add logic to validate data before it is saved (e.g., ensuring an age is not negative).

Security: It protects sensitive internal states from unauthorized modification.

Maintainability: You can change the internal implementation of a class without breaking the code that uses it.

Example : class Programmer {

private String name;

public String getName() { return name; }

public void setName(String name) {

this.name = name; }

Enter fullscreen mode

Exit fullscreen mode

}

public class Geeks {

public static void main(String[] args){

Programmer p = new Programmer(); p.setName("Geek");…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.