enum Flashcards
What is an enum?
It's short for “enumeration/enumerated type” -> Is like a fixed set of constant values. -> It can be a top‐level/nested-type. 🤯️⚠️📣️ Behind the scenes, an enum is a type of class that mainly contains static members 🤓️ Enum values are commonly written using Upper Snake Case -> OCKY_ROAD,MINT_CHOCOLATE_CHIP...
What about enum composition?
🤯️⚠️📣️ Enums can have more in them than just a list of values (members/constructors/methods*)
* including… static void main(String args[])
What about enum syntax?
🤯️⚠️📣️ The compiler requires the list of values must be always declared at first.
🤯️⚠️📣️ Semicolon is optional if enum is just composed of a list of values -> Otherwise it’s MANDATORY 👀️😬️
📝️ What are the most common enum helper methods (5)?
name()|values()|ordinal()|toString()|valueOf()
🕵♂️️🤓️🔎️ What is the Difference between name() and toString() ?
-> The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum to return a more user-friendly name.
What does the valueOf() method do?
🤯️⚠️📣️ The valueOf() method allow us to retrieve an enum value from a String.
-> If there is no enum constant for that value, it’ll throw ⚠️❌IllegalArgumentException❌⚠️
What about enum comparisson?
🤯️⚠️📣️ An enum is like any other type so when compared against other type compiler will complain:
❌ Season.WINTER == “WINTER” //Won’t compile (incomparable type)
⚠️ Season.WINTER.equals(“WINTER”) //false
How to use an ENUM in a SWITCH statement?
🤯️⚠️📣️ When using enums in switch statement the case branchesHow to use an ENUM in a SWITCH statement? only allow enum-value(s) -> 💥️name()
📝️ What about enum and access-modifiers?
-> An enum is implicitly public. Can’t be marked as ❌protected or ❌private
📝️ Can an enum be extended?
An enum can NOT be extended
-> public enum Extended
🛸️ How to Add Constructors, Fields, and Methods?
🤯️⚠️📣️ enum-value(s) may define a body where we can…
- > ✅ Invoke methods and constructor’s (curly braces are not mandatory)
- > ❌ member-fields can NOT be declared there (✅This can be done outside of it)
enum Season { WINTER("winter"), SUMMER("summer"), SPRING() { this.value = "sprIng"; //❌ }
📝️ How do we call an enum field/method?
- > Season.SUMMER.fieldName;
- > Season.SUMMER.methodName();
What about enum constructors?
🤓️ enum constructors are implicitly private, with the modifier being optional.
🕵♂️️👓️ This is reasonable since you can’t extend an enum
🕵♂️️👓️ The constructors can be called only within the enum itself
🧠️ An enum constructor will not compile if it contains a 💥️public💥️ or 💥️protected💥️ modifier.