0
0
Javaprogramming~30 mins

Encapsulation best practices in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Encapsulation Best Practices in Java
πŸ“– Scenario: You are creating a simple Java class to represent a bank account. You want to protect the account's balance so that it cannot be changed directly from outside the class. This is a common real-world need to keep data safe and controlled.
🎯 Goal: Build a Java class called BankAccount that uses encapsulation best practices: private fields, public getter and setter methods, and validation inside the setter.
πŸ“‹ What You'll Learn
Create a class called BankAccount with a private double field named balance
Add a public method getBalance() that returns the current balance
Add a public method setBalance(double amount) that sets the balance only if the amount is zero or positive
Do not allow direct access to the balance field from outside the class
πŸ’‘ Why This Matters
🌍 Real World
Encapsulation is used in real-world software to protect sensitive data like bank balances, passwords, or personal information.
πŸ’Ό Career
Understanding encapsulation is essential for writing safe, maintainable, and professional Java code in software development jobs.
Progress0 / 4 steps
1
Create the BankAccount class with a private balance field
Create a public class called BankAccount and inside it declare a private double variable named balance initialized to 0.0.
Java
Need a hint?

Use the keyword private before the double balance variable to hide it from outside the class.

2
Add a public getter method for balance
Inside the BankAccount class, add a public method called getBalance() that returns the value of the balance variable.
Java
Need a hint?

The getter method should be public and return the private balance value.

3
Add a public setter method with validation
Inside the BankAccount class, add a public method called setBalance(double amount) that sets the balance only if amount is greater than or equal to 0. Otherwise, do not change the balance.
Java
Need a hint?

Use an if statement to check if amount is not negative before setting balance.

4
Test the BankAccount class by setting and getting balance
Create a main method inside the BankAccount class. Inside it, create a BankAccount object called account. Use setBalance(100.0) to set the balance, then print the balance using getBalance().
Java
Need a hint?

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