0
0
Javaprogramming~30 mins

Why encapsulation is required in Java - See It in Action

Choose your learning style9 modes available
Why Encapsulation is Required in Java
πŸ“– Scenario: Imagine you are building a simple bank account system. You want to keep the account balance safe so that no one can change it directly without following the rules.
🎯 Goal: You will create a Java class that uses encapsulation to protect the account balance. You will see why encapsulation is important by controlling how the balance is accessed and changed.
πŸ“‹ What You'll Learn
Create a class called BankAccount with a private variable balance of type double
Add a public method getBalance() to return the current balance
Add a public method deposit(double amount) to add money to the balance only if the amount is positive
Add a public method withdraw(double amount) to subtract money from the balance only if the amount is positive and less than or equal to the balance
Create a main method to test the BankAccount class by depositing and withdrawing money and printing the balance
πŸ’‘ Why This Matters
🌍 Real World
Banking systems and many software use encapsulation to protect sensitive data like account balances or personal information.
πŸ’Ό Career
Understanding encapsulation is essential for writing secure and maintainable code in professional Java development.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance
Create a class called BankAccount with a private double variable named balance initialized to 0.
Java
Need a hint?

Use private double balance = 0; inside the class to keep the balance hidden.

2
Add public methods to get balance and deposit money
Add a public method getBalance() that returns balance. Add a public method deposit(double amount) that adds amount to balance only if amount is greater than 0.
Java
Need a hint?

Use if (amount > 0) to check the deposit amount before adding it.

3
Add a withdraw method with checks
Add a public method withdraw(double amount) that subtracts amount from balance only if amount is greater than 0 and less than or equal to balance.
Java
Need a hint?

Check both that amount is positive and does not exceed balance before subtracting.

4
Test the BankAccount class in main method
Create a main method inside BankAccount. Create an object account of BankAccount. Deposit 100, withdraw 30, then print the balance using System.out.println(account.getBalance()).
Java
Need a hint?

Use System.out.println(account.getBalance()) to show the final balance.