***Please comment what each line does if possible*** Write a Java class called B
ID: 3872330 • Letter: #
Question
***Please comment what each line does if possible***
Write a Java class called BankAccount.java (Parts of the code is given ), which has two fields name (String) and balance (double) and three methods deposit (double amount), withdraw(double amount) and displayBalance(). deposit method deposits the amount to the account causing the current balance to increase, withdraw method withdraws the amount causing the current balance to decrease and displayBalance method prints out the account name and the current balance separated by a comma. For example if name is Jake and balance is 40.0 it should print
Write a client program called BankAccountClient that creates a BankAccount object called B1 and assigns “John” to its name field and 1000 to balance field. Call the deposit method to deposit 500 to this account and call the display method to display the current balance. Then, withdraw 300 from this account and call the display method to display the current balance. Create another object called B2 and display the name and current balance for this object.
Sample Output:
Account holder: Current balance //After Deposit
John, 1500.0
Account holder: Current balance //After Withdrawal
John, 1200.0
Account holder: Current balance
Chris, 900.0
Explanation / Answer
public class BankAccount
{
private string name;
private double balance;
public BankAccount()
{
name = '';
balance = 0;
}
public BankAccount(String clientName, double intialBalance)
{
name = clientName; //Assign client name to name
balance = initialBalance; // Assign initial balance to current balance
}
// Function to deposit amount
public void deposit(double amount)
{
balance = balance + amount; // add deposited amount to the current balance
}
// function to withdraw amount.
public void withdraw(double amount)
{
balance = balance - amount; //deduct amount from the current balance
}
// to get the name and curent balance
public double displayBalance()
{
return name,balance;
}
}
public class BankAccount
{
public static void main(String[] args)
{
BankAccountClient B1 = new BankAccount(1000, john); //create B1 object
B1.deposit(500); // call deposit function to deposit 500
System.out.println(B1.displayBalance()); // display the current balance after deposit
B1.withdraw(300); // call withdraw function to withdraw 300
System.out.println(B1.displayBalance()); // display current balance
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.