Reputation: 47
How can enum constant be an object and access methods and have a constructor if it is static in nature.
How can the enum constant be objects and be static at the same time
Please refer the code below:-
enum Apple {
Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8);
private int price; // price of each apple
// Constructor
Apple(int p) {
System.out.println("Price: " + p);
price = p;
}
// default constructor, constructor overloading
Apple() {
price = -1;
System.out.println("Price: " + price);
}
int getPrice() { return price; }
}
class EnumDemo3 {
public static void main(String args[]) {
Apple ap;
// Display price of Winesap.
System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n");
// Display all apples and prices.
System.out.println("All apple prices:");
for(Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}
}
Upvotes: 2
Views: 857
Reputation: 250
Java doc:
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.
Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8);
Each of these will call a constructor in the beginning (when you execute Apple ap;
) with the price as stated in the brackets, nothing more.
Enum can also have methods. You are not restricted to simple getter and setter methods. You can also create methods that make calculations based on the field values of the enum constant. If your fields are not declared final you can even modify the values of the fields (bad practice, considering that the enums are supposed to be constants).
Enum instances are "static" (ie behave like static variables), but are not immutable - which is the answer to your question. Changing a field of an enum changes it for everyone (static).
It is good practice to make your fields final in an enum and to make them immutable.
private **final** int price;
Upvotes: 1