-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBankAccount.java
More file actions
76 lines (70 loc) · 2.55 KB
/
Copy pathBankAccount.java
File metadata and controls
76 lines (70 loc) · 2.55 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
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
/**
* 'balance' is the instance variable for the BankAccount class
* 'private' because we only want it to be updated with the 'methods' below
* Each time a new instance of BankAccount is created, new instance variables are created for the new object
*/
private double balance;
/**
Constructs a bank account with a zero balance. A constructor is a type of 'method' this code is used when an new object,
is created(instantiated). Note that the constructors have the same name as the class 'BankAccount'
*/
public BankAccount()
{
balance = 0;
}
/**
Constructs a bank account with a given balance.
'initialBalance' is a parameter sent by BankAccountTester and is used to initialize the balance for the new account
Parameter variables like 'initialBalance' are called local variables and cease to exist one the method code ends.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into the bank account.
'public' means that the method is part of the public interface for the BankAccount class and can be called from outside
'void' means that no data is returned
'deposit' is the name of the method
This method changes the value of the instance variable 'balance' so it is called a 'mutator' or 'setter'
@param amount the amount to deposit
*/
public void deposit(double amount)
{
balance = balance + amount;
}
/**
Withdraws money from the bank account.
Any amount of code can go inside a method
For example if we wanted to check to see if 'balance' was too low to support the withdrawal amount,
we could stop the withdrawal
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
if(balance - amount < 0 ) {
System.out.println("Only " + balance + " available. Withdraw not processed.");
}else {
balance -= amount;
}
}
/**
Gets the current balance of the bank account.
Notice there is no 'void' because the getBalance method returns the balance
However, since it is returning balance 'double' is indicated after public
A method that returns data is called an 'accessor' or 'getter'.
'getBalance' is a getter
@return the current balance
*/
public double getBalance()
{
return balance;
}
}