Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum in a parameterized constructor?

I have an assignment that asks me to create enumeration types. My question is, after I initialize them, how do I bring them into the default and parameterized constructors? i tried the following but it doesn't work... any ideas? Thanks

package magazine;
import paperPublication.PaperPublication;


public class Magazine extends PaperPublication {

    private enum paperQuality {LOW, NORMAL, HIGH};
    private enum issuingFrequency {WEEKLY, MONTHLY, YEARLY};

    public Magazine() {
        paperQuality = null;   //doesn't work
        issuingFrequency = null;    //doesn't work
    }

    public Magazine (double price, int numberOfPages, enum paperQuality  //doesn't work, enum issuingFrequency  //doesn't work) {

    }
}
like image 823
jsan Avatar asked Feb 06 '12 16:02

jsan


People also ask

Can you use enum in constructor?

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

Can enum be parameterized?

Enums can be parameterized.

Can we use enum in constructor Java?

Example: enum Constructor The constructor takes a string value as a parameter and assigns value to the variable pizzaSize . Since the constructor is private , we cannot access it from outside the class. However, we can use enum constants to call the constructor.

How do I use enum in another class?

To initialize the enum with values in another enum. Declare the desired enum as the instance variable. Initialize it with a parameterized constructor.


1 Answers

This is a type definition:

private enum paperQuality ...

But you don't actually have a field of that type declared. Try something like this:

private enum PaperQuality {...};
private PaperQuality paperQuality;

The first line defines the PaperQuality enum, defining the various values that any PaperQuality can hold. The second line creates a private field that is of that type, named paperQuality. The constructor could look like this:

public Magazine (double price, int numberOfPages, PaperQuality paperQuality) {
    ...
    this.paperQuality = paperQuality;
}
like image 177
StriplingWarrior Avatar answered Oct 01 '22 14:10

StriplingWarrior