Java Encapsulation: Protecting Data with OOP Principles

🚀 Java Series – Day 9 📌 Encapsulation in Java 🔹 What is it? Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It means wrapping data (variables) and methods (functions) together in a single unit called a class and restricting direct access to the data. In Java, encapsulation is achieved by: • Declaring variables as private • Providing public getter and setter methods to access and update the data This helps protect the internal state of an object. 🔹 Why do we use it? Encapsulation improves data security and code maintainability. For example: In a banking application, the account balance should not be directly modified by other classes. Instead, we use methods like deposit() or withdraw() to control how the balance is updated. 🔹 Example: class BankAccount { // Private variable (data hiding) private double balance; // Getter method public double getBalance() { return balance; } // Setter method public void setBalance(double amount) { if(amount > 0) { balance = amount; } } } public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(); account.setBalance(5000); System.out.println("Balance: " + account.getBalance()); } } 💡 Key Takeaway: Encapsulation protects data by restricting direct access and allowing modifications only through controlled methods. What do you think about this? 👇 #Java #OOP #Encapsulation #JavaDeveloper #Programming #BackendDevelopment

To view or add a comment, sign in

Explore content categories