Java Encapsulation

🔹 Java Encapsulation

Encapsulation is an OOP concept that wraps data (variables) and methods together in a class and restricts direct access to some of the object’s components.

It is also known as data hiding.


✅ 1. Key Features of Encapsulation

  1. Private variables – Restrict access from outside the class.

  2. Public getter and setter methods – Provide controlled access to variables.

  3. Enhances security and maintainability.

  4. Helps in flexible implementation and code modularity.


✅ 2. Syntax of Encapsulation

class ClassName {
private DataType variable; // private variable

// Getter method
public DataType getVariable() {
return variable;
}

// Setter method
public void setVariable(DataType variable) {
this.variable = variable;
}
}


✅ 3. Example: Encapsulation in Java

class Person {
private String name; // private variable
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) {
if(age > 0) { // validation
this.age = age;
} else {
System.out.println("Invalid age!");
}
}
}

public class Main {
public static void main(String[] args) {
Person p = new Person();

p.setName("Alice"); // using setter
p.setAge(25); // using setter

System.out.println("Name: " + p.getName()); // using getter
System.out.println("Age: " + p.getAge());
}
}

📌 Output:

Name: Alice
Age: 25

Direct access to name and age is not allowed because they are private. Access is only through getter and setter methods.


✅ 4. Advantages of Encapsulation

  1. Data Hiding – Prevents unauthorized access.

  2. Improved Security – Sensitive data cannot be modified directly.

  3. Code Flexibility – You can change the internal implementation without affecting outside code.

  4. Validation – Can validate inputs in setter methods.

  5. Better Maintainability – Keeps code modular and organized.


✅ 5. Key Points

Feature Description
Private variables Cannot be accessed directly from outside class
Public getter/setter Used to read/write private variables
Validation Can restrict invalid data using setters
OOP Principle Encapsulation is part of Abstraction and Data Hiding

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *