Unleashing the power of encapsulation #oopprogramming #encapsulation

preview_player
Показать описание
🔻 The real code example 🔻
Encapsulation is a principle in object-oriented programming that restricts access to an object's internal data and methods. This helps to protect the data from unauthorized editing and maintain the consistency of the object's state.

In Java it would look like that:

class BankAccount {
private double balance;

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

public void withdraw(double amount) {
if (balance - amount gte 0) {
balance -= amount;
} else {
}
}

public double getBalance() {
return balance;
}
}

class Main {
public static void main(String[] args) {
BankAccount ba = new BankAccount();

}
}

In the example code above, the BankAccount class has a balance attribute that is marked as private. This means that it can only be accessed within the class and not outside of it. To access or modify the balance, the class provides public methods such as deposit and withdraw which are used to perform these actions. This ensures that the balance can only be changed in a controlled and consistent manner, and that the data remains protected.

What are the benefits?
By encapsulating the data and behavior of a class, it is possible to change the implementation details of the class without affecting the code that uses it. This makes the code more flexible and maintainable, and helps to reduce the risk of bugs and errors.

❓❓❓ Do you have any other questions about encapsulation? Ask below 👇

#nikavscode #programmingtips #codingcommunity #oopprogramming #encapsulationinjava #developerslife #learnprogrammingfromphone
Рекомендации по теме