Java enumerations can be implemented using default, explicit, or parameterized constructors and methods. The default constructor automatically enumerates values like days of the week. A parameterized constructor allows initializing enumeration values with different attributes, like prices for apple varieties. An explicit constructor prints a message each time an enumeration value is instantiated.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
32 views
Java Enumeration Notes
Java enumerations can be implemented using default, explicit, or parameterized constructors and methods. The default constructor automatically enumerates values like days of the week. A parameterized constructor allows initializing enumeration values with different attributes, like prices for apple varieties. An explicit constructor prints a message each time an enumeration value is instantiated.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3
Implement Java enumeration by using default, explicit, parameterised
constructor and methods.
By using default constructor: Example program enum WeekDays { sun, mon, tues, wed, thurs, fri, sat } class Test { public static void main(String args[]) { WeekDays wk; // wk = WeekDays.sun; System.out.println("Today is "+wk); } } Output: Today is sun
By Using parameterised constructor:
Example Program enum Apples { Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8); int price; Apples(int p) { price = p; } int getPrice() { return price; } } public class EnumConstructor { public static void main(String[] args) { Apples ap; System.out.println("Winesap costs " + Apples.Winesap.getPrice() + " cents.\n"); System.out.println(Apples.GoldenDel.price); System.out.println("All apple prices:"); for(Apples a : Apples.values()) System.out.println(a + " costs " + a.getPrice() + " cents."); } } Output: Winesap costs 15 cents. 9 All apple prices: Jonathan costs 10 cents. GoldenDel costs 9 cents. RedDel costs 12 cents. Winesap costs 15 cents. Cortland costs 8 cents. In this example as soon as we declare an enum variable(Apples ap) the constructor is called once I'm it initialises value for every enumeration constant with value specified with them in parenthesis. By Using explicit constructor: Example Program enum Color { RED,BLUE,GREEN; Color() { System.out.println(“Constructor Called”); } } class Test { public static void main(String args[]) { Color c = Color.RED; } } Outut: Constructor Called Constructor Called Constructor Called