🎨
OOP

Enums

A Fixed Set of Choices
💡 Enum एक traffic signal जैसा है — सिर्फ़ RED, YELLOW, GREEN, इन तीन के अलावा कोई 4th color exist ही नहीं करता। Fixed, predefined choices।

enum एक special type है जिसमें सिर्फ़ fixed constants define होते हैं — जैसे Day.MONDAY, Day.TUESDAY।

ये normal String/int से better है क्योंकि compiler ग़लत value use होने ही नहीं देता — सिर्फ़ वही options allowed हैं जो तुमने define किए।

enum Level { LOW, MEDIUM, HIGH }

Level l = Level.MEDIUM;
if (l == Level.MEDIUM) System.out.println("Medium level!");
🎨
Enum एक traffic signal जैसा है — सिर्फ़ RED, YELLOW, GREEN, इन तीन के अलावा कोई 4th color exist ही नहीं करता। Fixed, predefined choices।
1 / 6
⚡ झट से Recap
  • Fixed set of named constants
  • Type-safe — ग़लत value allowed नहीं
  • Traffic-signal जैसा: सिर्फ़ predefined options
इस page में (4 subtopics)

Enum सिर्फ़ simple constants तक limited नहीं — हर constant के अपने fields और constructor भी हो सकते हैं। Constructor हमेशा private होता है (implicitly), क्योंकि enum constants सिर्फ़ declaration में ही बनती हैं, बाहर से "new" नहीं कर सकते।

Classic example: Planet enum जिसमें हर planet का mass और radius stored हो, और gravity calculate करने का method।

enum Planet {
  MERCURY(3.3e23, 2.4e6), EARTH(5.9e24, 6.4e6);
  final double mass, radius;
  Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
}

values() सब constants का array देता है (loop करने के लिए useful)। ordinal() constant की position (0 से) देता है declaration order में — लेकिन इस पर relying करना risky है अगर order बदल जाए future में, इसलिए careful use करो। name() constant का exact नाम String में देता है। valueOf("RED") String से enum constant बनाता है (अगर नाम match ना करे तो exception)।

for (Level l : Level.values()) {
  System.out.println(l.name() + " = " + l.ordinal());
}

switch statement में enum use करना बहुत clean होता है — case लिखते वक़्त enum नाम के prefix (Level.) की ज़रूरत नहीं पड़ती, और सारे possible values fixed होने की वजह से code safe रहता है (modern IDE भी warn कर सकता है अगर कोई case miss हो गया)।

Java special-purpose collections देता है enums के लिए: EnumMap (key के रूप में enum, HashMap से fast और memory-efficient क्योंकि internally array-based है) और EnumSet (enum constants का Set, bit-vector से implement होता है internally, बहुत fast operations)। जब भी key/elements enum हों, ये normal HashMap/HashSet से better choice हैं।