878187. Encapsulation in Java

Easy

Encapsulation in Java

Slug: encapsulation-in-java

Difficulty: Easy

Topic Tags: None

Company Tags: None

Summary

Encapsulation is a fundamental concept in object-oriented programming (OOP). It involves bundling data and methods that operate on that data within a single unit, called a class. This problem focuses on understanding the importance of encapsulation in Java.

Detailed Explanation

To demonstrate encapsulation, let's consider an example. Suppose we want to create a simple BankAccount class with attributes like account number, balance, and interest rate, as well as methods for depositing and withdrawing money. Without encapsulation, our code might look like this:

View on GeeksforGeeks
public class BankAccount {
    public int accountNumber;
    public double balance;
    public double interestRate;

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

    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds!");
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.