1. Create a class called Account with integer account number and double balance
ID: 3535670 • Letter: 1
Question
1. Create a class called Account with integer account number and double balance data fields. These data fields should be encapsulated. Create a default constructor that generates a random 8-digit account number and creates an account with that account number and a zero balance. (In the real world, the randomly generated account number would be checked against existing account numbers to ensure it is not a duplicate, but you do not need to do this). Overload the constructor by creating another one that takes the beginning balance as a parameter. The Account class should also have the following methods:
• checkBalance(): double that returns the current balance
• getAccountNumber(): int that returns the account number
• deposit(double: amount): void that deposits the specified amount
• withdraw(double: amount): String that withdraws the specified amount if doing so does not cause an overdraft and returns “OK†successful or “Withdrawal would overdraft account†if unsuccessful.
Draw the UML diagram for your class and implement it in Java.
2. Create a subclass of the Account class called CheckingAccount. This class should have a constant called MAXCHECKS, an array of MAXCHECKS objects called checks, and an integer count of how many checks have been processed called numChecks. Each element of the checks array will contain an integer check number and a double amount for any check that is processed on the account. The CheckingAccount subclass should also have a processCheck(checkNumber: int, amount: double): String method that processes a check drawn on the account by withdrawing the amount from the balance if doing so does not cause an overdraft. The processCheck method should return “OK†if successful and the string “Processing check <checkNumber> would overdraft account†where <checkNumber is the relevant check number. Draw the UML diagram for your class and implement it in Java.
Explanation / Answer
import java.util.Random;
public class Account {
private int accno;
private double balance;
public Account() {
super();
this.accno = get8digitAccNo();
this.balance = 0;
}
public Account(double balance) {
super();
this.accno = get8digitAccNo();
this.balance = balance;
}
private int get8digitAccNo() {
Random r = new Random();
String acno = "";
for(int i=0; i< 8; i++) {
acno += r.nextInt(9);
}
return Integer.parseInt(acno);
}
public double checkBalance() {
return balance;
}
public int getAccountNumber(){
return accno;
}
public void deposit(double amount){
balance += amount;
}
public String withdraw(double amount){
if(amount <= balance) {
balance -= amount;
return "OK";
}
else {
return "Unsuccessful";
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.