DEV Community

Cover image for Understanding Encapsulation in Java: A Friendly Guide
Kudzai Murimi
Kudzai Murimi

Posted on

10 2 2 2 2

Understanding Encapsulation in Java: A Friendly Guide

Hello, Coders!

Thank you for being with in this this journey of learning Java whereby we share the knowledge, last time we discussed about Java basics, today we have something different on the table.

Let’s talk about Object-Oriented Programming (OOP) in Java. It’s a way of organizing code to make it simple, clear, and easy to manage. In this article, we’ll focus on Encapsulation, and next time, we’ll move on to Inheritance.

What is Encapsulation?

Think of encapsulation like wrapping a candy in shiny paper. The wrapper protects the candy and controls how you can get to it. In programming, encapsulation means:

  • Hiding the details of a class (like the candy inside).
  • Allowing access only through specific methods (like unwrapping the candy carefully).

Why is Encapsulation Important?

  1. Protects Data: It keeps your data safe from being accessed or changed in ways you don’t want.
  2. Controlled Access: You can decide how the data can be read or updated using methods like get and set.
  3. Easier to Fix: If you change how your class works inside, the rest of your program stays unaffected.

Where Do We Use Encapsulation?

  1. User Accounts: For example, you can hide passwords and only allow setting or reading them using secure methods.
  2. Banking Apps: Keep account balances private and use methods to deposit or withdraw money in a controlled way.

How Do We Use Encapsulation in Java?

Java uses access modifiers to control access to data:

  • private: Only the class itself can use it.
  • protected: Accessible within the same package and by subclasses.
  • public: Accessible by any class.

Here’s a simple example:

public class BankAccount {
    // Keep the balance private
    private double balance;

    // Set the initial balance using a constructor
    public BankAccount(double initialBalance) {
        balance = initialBalance;
    }

    // Provide a method to see the balance
    public double getBalance() {
        return balance;
    }

    // Add money to the account
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    // Remove money from the account
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • The balance is private, so no one outside the class can access it directly.
  • Public methods like getBalance, deposit, and withdraw provide safe ways to interact with the balance.

Practice Your Skills

Here are some great resources to learn more about encapsulation:

Encapsulation helps you write secure, organized, and easy-to-update code. In the next article, we’ll explore Inheritance, which lets you create new classes based on existing ones.

If you have tips or resources for learning Java, share them in the comments.

Always keep it in mind that:

Growing as a developer is a journey, not a race. Be patient with yourself, but always try to do better than yesterday.

Happy Coding

Image description

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (7)

Collapse
 
devnenyasha profile image
Melody Mbewe

Wow 😍 This is fantastic! I love how you explained the concept using the candy analogy—it really makes the idea of protecting data clear and relatable. The examples you provided, especially the BankAccount class, are practical and easy to understand. I appreciate the emphasis on the importance of controlled access and how encapsulation contributes to secure and maintainable code. Looking forward to the next article on inheritance! Keep up the great work!

Collapse
 
respect17 profile image
Kudzai Murimi

Thank you so much for the feedback, it's just a game

we study, we share
we discover, we share
Go along with as i proceed the the Java Path,
I will appreciate it if you also share some links 😊

Collapse
 
madzimai profile image
Netsai
Collapse
 
madzimai profile image
Netsai

I found it very helpful. Thank you for sharing!

Collapse
 
devmercy profile image
Mercy

Thank you for sharing, well explained👏

Collapse
 
taqmuraz profile image
Taqmuraz • Edited

I guess, some hacker may access balance through BankAccount object pointer and read or change value of balance private field.
If object stores really important data, it is not safe to give away the pointer to that object.
Really safe solution would be to have a private hash-table somewhere and to give user's UUID instead.
Something like

public class Balances {
  private static final HashMap<UUID, Double> balances = ...;
  public static void deposit(UUID account, double amount) { ... }
  public static void withdraw(UUID account, double amount) { ... }
  public static double getBalance(UUID account) { ... }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
respect17 profile image
Kudzai Murimi

Well, thanks hey-- i see what you mean

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up