← Back to Chapters

Encapsulation in Java

? Encapsulation in Java

? Quick Overview

Encapsulation is a core principle of Object-Oriented Programming in Java. It means binding data (variables) and methods together inside a class and controlling access to that data using access modifiers.

? Key Concepts

  • Data hiding using private variables
  • Controlled access via getters and setters
  • Improves security and maintainability
  • Prevents direct modification of class data

? Syntax / Theory

In Java, encapsulation is implemented by:

  • Declaring class variables as private
  • Providing public getter and setter methods

? Code Example

? View Code Example
// Encapsulated class with private data and public methods
class Student {
private int age;

public void setAge(int age) {
this.age = age;
}

public int getAge() {
return age;
}
}

class Main {
public static void main(String[] args) {
Student s = new Student();
s.setAge(20);
System.out.println(s.getAge());
}

? Live Output / Explanation

Output

20

The age variable cannot be accessed directly. It is safely modified and read using setter and getter methods.

? Interactive Demo: Bank Account

This demo simulates an encapsulated BankAccount class. The balance variable is private. You cannot change it directly; you must use the public methods which contain validation logic.

? private double balance;
$1000
> System initialized. Current balance is $1000.

✅ Tips & Best Practices

  • Always keep class fields private
  • Validate data inside setter methods
  • Expose only required behavior
  • Encapsulation helps achieve loose coupling

? Try It Yourself

  • Create a BankAccount class with private balance
  • Add deposit() and withdraw() methods
  • Prevent negative balance using validation