From the course: Learning Java 11

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Solution: Bank account balance

Solution: Bank account balance - Java Tutorial

From the course: Learning Java 11

Solution: Bank account balance

- [Instructor] Let's implement a Java class to represent a bank account. This class has three different methods, withdraw, deposit, and get balance. Let's start with get balance. We already have an instance variable to keep track of the current balance, so let's return it. Now, let's implement deposit. Before incrementing the balance, we'll want to double check that the amount is a positive number. We can use an if statement. If the amount is greater than zero, we'll add it to the balance. Finally, the withdrawal method. We can only withdraw if the amount is less than or equal to the balance. Let's add that if statement. If this is true, we can subtract the amount from the balance. Both the withdraw and deposit methods return void, so there's nothing to return. Let's run it. Our implementation works as expected. We can deposit an amount, withdraw an amount, and retrieve the account balance correctly with this class.

Contents