DEV Community

Srinivasan. R
Srinivasan. R

Posted on

Encapsulation

Introduction

Object-Oriented Programming (OOP) is one of the most widely used programming paradigms in modern software development.
One of the key principles of OOP is Encapsulation, which helps developers protect data and maintain clean code structure.

In this article, we will understand what encapsulation is and how to implement it in Java.

What is Encapsulation?

Encapsulation means wrapping data (variables) and methods (functions) together inside a single unit called a class.

It also helps to hide sensitive data from direct access by making variables private and controlling access through methods.

**Java Example

class BankAccount {

private double balance;

public void deposit(double amount) {
    balance = balance + amount;
}

public double getBalance() {
    return balance;
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {

    BankAccount acc = new BankAccount();
    acc.deposit(1000);

    System.out.println("Balance: " + acc.getBalance());
}
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)