Enums
The Aims
This lab will give you the chance to practice working with enumerated types
Creating an enum
-
Create a new enum called
AccountType. -
Define the values for the enum of
CHECKING,SAVING,CREDIT_CARD.
Click here to see the sample solution
public enum AccountType {
CHECKING, SAVING, CREDIT_CARD
}
Using an enum
-
Add an additional private field to the Account class to store the Account type.
-
Create a getter and setter method for the account type.
-
In the class' default constructor, set the account type to CHECKING.
-
Edit the other constructor to receive a account type as one of its parameters.
-
Update the toString method to print out the Account Type.
-
Delete and re-create the hashcode and equals methods so that they now include the account type.
-
Edit your code in the TestAccount2 class to supply an account type.
Click here to see the sample solution
public class Account {
private double balance;
private String name;
private AccountType accountType;
...
public Account(double balance, String name, AccountType accountType) {
this.balance = balance;
this.name = name;
this.accountType = accountType;
}
public Account() {
this.balance = 50;
this.name = "John";
this.accountType = AccountType.CHECKING;
}
public AccountType getAccountType() {
return accountType;
}
public void setAccountType(AccountType accountType) {
this.accountType = accountType;
}
...
@Override
public String toString() {
return "Account [balance=" + balance + ", name=" + name + ", account type: " + accountType + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(balance);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (Double.doubleToLongBits(balance) != Double.doubleToLongBits(other.balance))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (accountType != other.accountType)
return false;
return true;
}
}
public class TestAccount2 {
public static void main(String[] args) {
Account[] accounts = new Account[5];
accounts[0] = new Account(1000.0, "Alice", AccountType.CHECKING);
accounts[1] = new Account(2000.0, "Bob", AccountType.CHECKING);
accounts[2] = new Account(1500.0, "Charlie", AccountType.SAVING);
accounts[3] = new Account(1500.0, "Charlie", AccountType.SAVING);
accounts[4] = new Account(2500.0, "Eve", AccountType.CREDIT_CARD);
...
}
}