Understanding Encapsulation in Java: A Friendly Guide
Kudzai Murimi

Kudzai Murimi @respect17

About: FullStack Developer and Content Writer

Location:
Capetown, South Africa
Joined:
Nov 30, 2022

Understanding Encapsulation in Java: A Friendly Guide

Publish Date: Dec 22 '24
18 8

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

Comments 8 total

  • Melody Mbewe
    Melody MbeweDec 22, 2024

    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!

  • Mercy
    MercyDec 22, 2024

    Thank you for sharing, well explained👏

  • Netsai
    NetsaiDec 22, 2024

    I found it very helpful. Thank you for sharing!

  • Janith Madusanka
    Janith MadusankaDec 23, 2024

    Best Programming Solutions
    Get the best programming codes -5000+ codes available for you to buy or download for free! shorturl.at/uxgXQ

  • Taqmuraz
    TaqmurazDec 23, 2024

    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
Add comment