DEV Community

MOHAMED ABDULLAH
MOHAMED ABDULLAH

Posted on

Encapsulation

Encapsulation is the process of hiding the internal details of a class and only showing essential information through methods. It’s like putting important data inside a capsule and giving access through controlled ways.

Key Features of Encapsulation

Data members (variables) are marked private

Access to them is given through public getter and setter methods

Helps to maintain control over data

Improves modularity and code security

Structure of Encapsulation

class ClassName {
// 1. Private variables (hidden from outside)
private DataType variable;

// 2. Public getter method
public DataType getVariable() {
    return variable;
}

// 3. Public setter method
public void setVariable(DataType value) {
    this.variable = value;
}
Enter fullscreen mode Exit fullscreen mode

}

Benefits of Encapsulation

Security Data is not directly accessible by outside classes

Control You decide how data is accessed or modified

Flexibility Easy to change one part of the code without affecting
others

Reusability Encapsulated classes are easier to reuse in otherprograms

EXAMPLE:

public class Student {
private String name;
private int age;

// Getter for name
public String getName() {
    return name;
}

// Setter for name
public void setName(String name) {
    this.name = name;
}

// Getter for age
public int getAge() {
    return age;
}

// Setter for age
public void setAge(int age) {
    this.age = age;
}
Enter fullscreen mode Exit fullscreen mode

}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.setName("Abdullah");
student.setAge(22);

    System.out.println("Student Name: " + student.getName());
    System.out.println("Student Age: " + student.getAge());
}
Enter fullscreen mode Exit fullscreen mode

}
output:

Student Name: Abdullah
Student Age: 22

referel links :

1 : https://docs.oracle.com/javase/tutorial/java/javaOO/encaps.html
2 : https://www.w3schools.com/java/java_encapsulation.asp

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.