public class BankAccount { public double balance; public BankAccount () { balanc
ID: 3770754 • Letter: P
Question
public class BankAccount { public double balance; public BankAccount () { balance - 0.0;} public void withdraw (double amount) { balance - amount; } public void deposit (double amount) { balance +- amount; } } Since this is a checking account, you are required to enforce an invariant that the balance is never negative. With this invariant in mind, Explain why the given code is a bad design for the abstract data type BankAccount. Write down a better implementation for BankAccount in Java (or your favorite OO language). For each method in your implementation, clearly specify precondition, postcondition and side effects in comments, as we did in Lecture 31.Explanation / Answer
a)
The given code is a bad design for the abstract data type BankAccount because for the method withdraw(), when certain amount of money is withdrawn from the account the balance of the account is reduced. There is a chance of obtaining negative balance at some stage, which is never possible. So, it is a bad design.
b)
BankAccount.java:
public class BankAccount
{
public double balance;
public BankAccount()
{
balance=0.0;
}
public void BankBalance(double bal)
{
this.balance=bal;
}
public void withdraw(double amount)
{
double minBal=500.0;
if(balance<amount || balance<minBal || balance == minBal)
{
System.out.println("Cannot withdraw!!! Account is with minimum balance.");
}
else
{
balance-=amount;
System.out.println(balance);
}
}
public void deposit(double amount)
{
balance+=amount;
System.out.println(balance);
}
}
Bank.java:
public class Bank extends BankAccount
{
public static void main(String[] args)
{
BankAccount b = new BankAccount();
b.BankBalance(400.0);
b.withdraw(500.0);
b.withdraw(1100.0);
b.deposit(1500.0);
}
}
Sample Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.