tags:

views:

75

answers:

2

I have one class that declares an enumeration type as:

public enum HOME_LOAN_TERMS {FIFTEEN_YEAR, THIRTY_YEAR};

Is this type usable in another class? I'm basically trying to complete a homework assignment where we have two types of loans, and one loanManager class. When I try to use the HOME_LOAN_TERMS.THIRTY_YEAR in my loanManager class that does not extend or implement the loan class, I get an error saying it 'cannot find symbol HOME_LOAN_TERMS.' So I did not know if my loanManager class needed to implement the two different loan classes. Thanks.

I'm currently working on this so I know it's not complete, but here is where I tried to use it:

import java.util.ArrayList;

public class AcmeLoanManager 
{
    public void addLoan(Loan h)
    {
        loanArray.add(h);
    }
    /*
    public Loan[] getAllLoans()
    {
    }

    public Loan[] findLoans(Person p)
    {
    }

    public void removeLoan(int loanId)
    {
    }
    */
    private ArrayList<Loan> loanArray = new ArrayList<Loan>(5);

    public static void main(String[] args)
    {
        AcmeLoanManager aLoanManager = new AcmeLoanManager();
        Person aPerson = new Person("Crystal", "Twix", "619-111-1234", "[email protected]");
        HomeLoan aHomeLoan = new HomeLoan(aPerson, 400000, 5, HOME_LOAN_TERMS.THIRTY_YEAR);
        aLoanManager.addLoan(aHomeLoan);
    }
}
+7  A: 

You have to specify the type:

HOME_LOAN_TYPES type = HOME_LOAN_TYPES.FIFTEEN_YEAR;

By the way, don't use this naming convention for enums. Use the same camel case you do for classes so:

public enum HomeLoanType {
  FIFTEEN YEAR,
  THIRTY_YEAR
}

If you don't want to specify the type you can do a static import:

import static package.name.HomeLoanType.*;

...

HomeLoanType type = FIFTEEN_YEAR;

Lastly, one of the best things about Java enums is they can have state and behaviour. For example:

public enum HomeLoanType {
  FIFTEEN YEAR(15),
  THIRTY_YEAR(30);

  private final int years;

  HomeLoanType(int years) {
    this.year = years;
  }

  public int getYears() {
    returns years;
  }
}
cletus
+1 I had never heard of static import
Romain Hippeau
@Romain they can be handy but they can also makes things confusing as suddenly when you read the code it might not be clear as to the source of a partciular enum value.
cletus
+1  A: 

Yes, since it's public you can use it from another class.

If it's in your Loan class you write Loan.HOME_LOAN_TERMS.FIFTEEN_YEAR to refer to it from a different class.

Tom
Why do you have to use the Loan. qualifier for this enum type, but not for another class type? For example, I use my Person class in my LoanManager class and I don't get an error of symbol not found, but do for the enum type? Thanks.
Crystal
Because the enum's contained within that class, you can move it to it's own file and then you don't need to refer to it like that. In fact moving it to its own file would probably be best (separate the concerns).
Tom