0
0
Javaprogramming~15 mins

Private access modifier in Java - Mini Project: Build & Apply

Choose your learning style8 modes available
folder_codeUnderstanding the Private Access Modifier in Java
📖 Scenario: Imagine you are creating a simple Java class to represent a bank account. You want to keep the account balance safe so that it cannot be changed directly from outside the class.
🎯 Goal: You will create a Java class with a private variable to store the balance, then add methods to safely access and update the balance.
📋 What You'll Learn
Create a class called BankAccount
Add a private variable called 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
Add a public method withdraw(double amount) to subtract money from the balance if enough funds exist
Print the balance after deposits and withdrawals
💡 Why This Matters
🌍 Real World
In real banking software, sensitive data like account balances must be protected from direct changes to avoid errors or fraud.
💼 Career
Understanding access modifiers like private is essential for writing secure and maintainable code in professional Java development.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance variable
Create a class called BankAccount with a private double variable named balance initialized to 0.0.
Java
💡 Need a hint?

Use the keyword private before the variable balance to restrict access.

2
Add a public method to get the balance
Add a public method called getBalance() that returns the value of the private variable balance.
Java
💡 Need a hint?

The method should be public so other classes can call it.

3
Add deposit and withdraw methods
Add two public methods: deposit(double amount) to add amount to balance, and withdraw(double amount) to subtract amount from balance only if balance is enough.
Java
💡 Need a hint?

Use an if statement in withdraw to check if there is enough balance.

4
Create a main method to test the BankAccount class
Add a main method inside BankAccount that creates an object called account, deposits 100.0, withdraws 30.0, and then prints the balance using System.out.println.
Java
💡 Need a hint?

Use System.out.println(account.getBalance()); to print the balance.