Enum fields
- Java course
- Beginner
- Lesson 102/116
- 4 min
Learn to add fields to enum constants.
Add fields to an enum
An enum constant can carry extra information. To do this you add a field and a constructor inside the enum. Each constant passes a value to the constructor.
enum Coffee {
SMALL("küçük"), LARGE("büyük");
String label;
Coffee(String label) {
this.label = label;
}
}The constructor is always private; no new constants can be created from outside. The value is written in parentheses next to the constant and the constructor receives it. This way each constant comes with its own data and the code reads better.
Accessing fields
You access an enum constant's field with a dot. The constructor fills the field; you only read it. The field is usually made final, since constants do not change.
Coffee c = Coffee.LARGE;
System.out.println(c.label); // büyükMultiple fields can be added too, for example a label and a price. The constructor parameter order must be respected. Making fields public final allows outside access; making them private and returning them via a method is also common.
Practice Print the coffee label
Define a Coffee enum with SMALL and LARGE constants. Each constant takes a String label (SMALL gets küçük, LARGE gets büyük). Print the label of the LARGE constant.
Starter code
public class Main {
public static void main(String[] args) {
// Define the Coffee enum, print the label of LARGE
}
}
// Define the Coffee enum hereSample solution
enum Coffee {
SMALL("küçük"), LARGE("büyük");
String label;
Coffee(String label) { this.label = label; }
}
// inside main:
System.out.println(Coffee.LARGE.label);Expected output
büyük
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pass a value to the constructor
enum Coffee {
SMALL("küçük"), LARGE("____");
String label;
Coffee(String label) { this.label = label; }
}
enum Coffee {
SMALL("küçük"), LARGE("büyük");
String label;
Coffee(String label) { this.label = label; }
}
Explanation: the LARGE constant gets the label 'büyük'.
2 What access level is an enum constructor?
- public
- private Correct answer
- default (package)
- protected
Explanation: an enum constructor is always private; no new constants can be created from outside.
3 Match each concept to its description
| Term | Meaning |
|---|---|
label |
Constant's label |
Coffee(String) |
Constructor |
this.label |
Assignment |
SMALL("küçük") |
Value passed |