Encapsulation


Encapsulation:

Definition: 
              Encapsulation is the bundling of data (attributes) and methods that operate on that data within a class, while controlling access to them.
 
Explanation  : 
              Access modifiers (public, private, protected) restrict access to class members. Getters and setters provide controlled access to attributes, maintaining data integrity.
 
Example:

class BankAccount {

    private double balance;

 

    public void deposit(double amount) {

        if (amount > 0) {

            balance += amount;

        }

    }

 

    public double getBalance() {

        return balance;

    }

}

 

public class Main {

    public static void main(String[] args) {

        BankAccount account = new BankAccount();

        account.deposit(1000);

        double balance = account.getBalance();

        System.out.println("Balance: " + balance); // Output: Balance: 1000.0

    }

}

Comments

Popular posts from this blog

Installing MySQL and MySQL Workbench

Java Program to Check Palindrome Number

Scenario : 1