Java  By Harsh Upadhye

Java By Harsh Upadhye

Written and Code by - Harsh Upadhye

Table of contents

No heading

No headings in the article.

Encapsulation :

Encapsulation is a technique in object-oriented programming where the internal state and behavior of an object are hidden from the outside world. It is one of the four fundamental principles of object-oriented programming, along with inheritance, polymorphism, and abstraction. Encapsulation allows for data hiding, which can prevent data from being tampered with or accessed in an unintended way. It also allows for a level of control over how an object is used and accessed, which can help to create more robust and maintainable code.

Here is an example of encapsulation in Java:

public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        balance = initialBalance;
    }

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

    public boolean withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
            return true;
        } else {
            return false;
        }
    }

    public double getBalance() {
        return balance;
    }
}

In this example, the balance a variable is private, meaning that it can only be accessed within the BankAccount class. The deposit() and withdraw() methods can change the value of balance, but they cannot be accessed from outside the class. The only way to access the balance is through the getBalance() method which is public. This way we ensure that the balance of the account can only be changed in a controlled way and that it cannot be accessed or modified by any other part of the code.
Encapsulation in Java is a technique for hiding the internal implementation details of an object, and instead exposing a public interface that can be used to interact with the object.

For example, imagine you have a class called "BankAccount" that represents a bank account. This class might have a number of private variables, such as the account balance and the account number, that are used to store information about the account. These variables should be private, so that they cannot be accessed or modified by code outside the class.

Instead, the class should provide public methods, such as "deposit()" and "withdraw()", that can be used to change the account balance. These methods can access and modify the private variables, but they can only be called from code outside the class.

This way, the internal implementation details of the class are hidden from the outside world, and the class can be used in a consistent and predictable way, without worrying about breaking the internal state of the class.

By encapsulating the internal state and behavior of an object, we can make the code more robust, easier to maintain, and less prone to errors.

Did you find this article valuable?

Support Harsh Upadhye by becoming a sponsor. Any amount is appreciated!