-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBankAccount.java
More file actions
100 lines (84 loc) · 2.26 KB
/
BankAccount.java
File metadata and controls
100 lines (84 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package Bank;
import java.util.*;
abstract class BankAccount {
//initializes random variable
private static final Random rng = new Random();
//has a database of bank accounts
private static final Map<Long,BankAccount> accounts = new HashMap<Long,BankAccount>();
//amount of money in account
public double balance;
//id of account
public long id;
//name of owner of account
public String name;
/*
* precondition: requires name != null && amount > 0;
* ensures this.name == name && balance == amount && id == Math.abs(rng.nextLong());
*/
public BankAccount(double amount, String name) {
Objects.requireNonNull(name);
if(amount < 0) {
throw new IllegalArgumentException();
}
this.setBalance(amount);
this.name = name;
boolean idAssigned = false;
while (!idAssigned) {
this.id = Math.abs(BankAccount.rng.nextLong());
if (!BankAccount.accounts.containsKey(this.id)) {
BankAccount.accounts.put(this.id, this);
idAssigned = true;
}
}
}
public /* pure */ long getId() {
return id;
}
public /* pure */ double getBalance() {
return balance;
}
public void setBalance(double amount) {
this.balance = amount;
}
public /* pure */ String getName() {
return name;
}
/*
* requires amount > 0
* ensures \result == balance == \old(balance) + amount
*/
public void deposit(double amount) {
this.setBalance(this.balance + amount);
}
/*
* requires amount > 0
* ensures \result == balance == \old(balance) - amount
*/
public void withdraw(double amount) {
this.setBalance(this.balance - amount);
}
public abstract void transfer(double amount, BankAccount other);
/*
* ensures true
* */
@Override
public int hashCode() {
return Objects.hash(id);
}
/*
* esnures /result == false if obj == false && /result == this== obj
* */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BankAccount other = (BankAccount) obj;
return Objects.equals(accounts, other.accounts)
&& Double.doubleToLongBits(balance) == Double.doubleToLongBits(other.balance)
&& Objects.equals(name, other.name);
}
}