Java

OOP GUIDE / WORK

 

BANKACCOUNT CLASS SOLUTIONS

 

 

TASK – PART 1 – BANKACCOUNT CLASS

 

Here is my solution:

 

 

public class BankAccount

{

     //INSTANCE VARIABLES

    

     public double balance;

     public String firstName;

     public String lastName;

    

     //CONSTRUCTOR

    

     public BankAccount(String fn, String ln)

     {

           balance = 0.0;

           firstName = fn;

           lastName = ln;

     }

    

     //INSTANCE METHODS

    

     public void deposit(double amount)

     {

           balance = balance + amount;

     }

    

     public void withdraw(double amount)

     {

           balance = balance - amount;

     }

    

     public String fullName()

     {

           return firstName + " " + lastName;

     }

    

     public boolean inOverDraft()

     {

           if (balance < 0)

                return true;

           else

                return false;

     }

    

     public String toString()

     {

           return fullName() + "($" + balance + ")";  

     }

}

 

 

 

TASK – PART 2 – TESTING YOUR BANKACCOUNT CLASS

 

Here is my solution:

 

 

public class BankAccountTester

{

     public static void main(String[] args)

     {

           BankAccount ba = new BankAccount("Jimbob", "Twoshoes");

           System.out.println(ba);

          

           ba.deposit(1000);

           System.out.println(ba);

          

           ba.withdraw(10);

           System.out.println(ba);

 

           ba.withdraw(996);

           System.out.println(ba);

          

           if (ba.inOverDraft())

           {

                System.out.println("BankAccount status: Bad");

           }

           else

           {

                System.out.println("BankAccount status: Good");

           }

                     

           ba.deposit(50);

           System.out.println(ba);

          

           if (ba.inOverDraft())

           {

                System.out.println("BankAccount status: Bad");

           }

           else

           {

                System.out.println("BankAccount status: Good");

           }   

     }

}

 

 

The above code outputs the following:

 

Jimbob Twoshoes($0.0)

Jimbob Twoshoes($1000.0)

Jimbob Twoshoes($990.0)

Jimbob Twoshoes($-6.0)

BankAccount status: Bad

Jimbob Twoshoes($44.0)

BankAccount status: Good