Home > Back-end >  Using enum in an class constructor
Using enum in an class constructor

Time:10-31

I'm doing some revision for an upcoming exam and I'm a little confused about the use of enums in the constructor for an object.

This is the code I've come up with for class country() where the question asks to include the UN member status for each country object.

public class Country {

    private String name;
    private enum Status {NOTMEMBER, GENERALASSEMBLY, TEMPORARYSC, PERMANENTSC};
    private boolean duesPaid;

    public Country(String name, Status status, boolean duesPaid) {
        this.name = name;
        this.Status = status;
        this.duesPaid = duesPaid;
    }

    public String getName() {
        return name;
    }

    public Status getStatus() {
        return Status;
    }

    public boolean hasPaidDues() {
        return duesPaid;
    }

    public void changeStatus(Status status) {
        this.Status = status;
    }
}

I was wondering how to properly pass the enum as a parameter. I understand the syntax for an enum is enum.VARIABLE, but everything I have tried in that vein hasn't been working properly. Is there a better way to do it?

CodePudding user response:

Your enum declaration must be public, otherwise callers cannot access its values:

public enum Status {NOTMEMBER, GENERALASSEMBLY, TEMPORARYSC, PERMANENTSC};
public class Country 
{
    private String name;
    private boolean duesPaid;
    private Status status;
    
    public Country(String name, Status status, boolean duesPaid) {
        this.name = name;
        this.Status = status;
        this.duesPaid = duesPaid;
    }

    // getters   setters left out for brevity
}

If declared within the class, it must still be public and can then be accessed with Country.Status, e.g. Country.Status.NOTMEMBER.

  • Related