Encapsulation in Java with an example

Encapsulation is the principle of enclosing data and methods into a single unit (i.e., an object) and restricting external access to the object's internal data. This contributes to the object's internal state remaining consistent and its behavior being controllable by a well-defined set of methods.

Java encapsulation example

Consider the following program to be an example of encapsulation in Java. I used proper commenting to aid comprehension, but I also explained the program after the output.

Java Code
public class MyClass {
    // Private instance variables can only be accessed by methods within the class
    private int num;
    private double bal;

    // Constructor sets initial values for private instance variables
    public MyClass(int num, double initialBalance) {
        this.num = num;
        this.bal = initialBalance;
    }

    // Public getter methods provide controlled access to private instance variables
    public int getAccountNumber() {
        return num;
    }

    public double getBalance() {
        return bal;
    }

    // Public methods allow balance to be modified, but only through controlled access to private instance variable
    public void deposit(double amount) {
        bal += amount;
        System.out.println("A deposit of $" + amount + " has been made. The new balance is $" + bal);
    }

    public void withdraw(double amount) {
        if (bal < amount) {
            System.out.println("Insufficient funds.");
        } else {
            bal -= amount;
            System.out.println("A withdrawal of $" + amount + " has been made. The new balance is $" + bal);
        }
    }

    public static void main(String[] args) {
        // Create an object of MyClass
        MyClass myObject = new MyClass(123456, 1000.0);
        
        // Access private instance variable through public getter method
        System.out.println("Account number: " + myObject.getAccountNumber() + "\n");
        
        // Modify private instance variable through public method
        myObject.deposit(500.0);
        myObject.withdraw(200.0);
        
        // Access private instance variable through public getter method
        System.out.println("\nCurrent balance: $" + myObject.getBalance());
    }
}
Output
Account number: 123456

A deposit of $500.0 has been made. The new balance is $1500.0
A withdrawal of $200.0 has been made. The new balance is $1300.0

Current balance: $1300.0

Encapsulation is a mechanism that combines data and methods that operate on that data into a single unit, limiting access to the data from outside that unit. Encapsulation is demonstrated in this program by declaring the instance variables "num" and "bal" as "private," which means they can only be accessed within the class.

Public getter methods getAccountNumber() and getBalance() are provided to allow controlled access to these private variables. These methods are accessible from outside the class and return the private variable values.

Similarly, the public methods deposit() and withdraw() allow the balance to be changed, but only with restricted access to the private variable bal. This ensures that the balance can only be changed in accordance with the rules specified in these methods, rather than by modifying the private variable directly.

A MyClass object is created in the main method, and the private variables are accessed and modified using the public getter and modifier methods. This shows how encapsulation allows controlled access to a class's private variables while keeping implementation details hidden from outside the class.

Important information regarding encapsulation in Java

Here are several essential considerations when working with encapsulation in Java:

Advantages of encapsulation in Java

Disadvantages of encapsulation in Java

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!