Enums Are Classes: toString, equals, and hashCode
What you'll learn: You'll discover that enums aren't just simple constants—they're full-fledged classes that automatically inherit well-implemented methods from Java's Enum class.
The Surprising Truth About Enums
When you declare an enum like enum Color { RED, GREEN, BLUE }, Java doesn't create mere labels. Behind the scenes, your enum becomes a class that extends the built-in java.lang.Enum class. This inheritance gives every enum constant powerful, ready-to-use methods without you writing a single line of extra code.
toString: Human-Readable Names for Free
Every enum constant automatically gets a toString() method that returns its name as a string:
enum Status { PENDING, APPROVED, REJECTED }
Status current = Status.APPROVED;
System.out.println(current.toString()); // Prints: APPROVED
This is incredibly useful for logging and debugging—the name is already readable, no conversion needed.
equals: Identity-Based, Always Correct
Enum constants use reference equality (like ==), but equals() works perfectly too. Since there's exactly one instance of each constant, comparing them is foolproof:
Status s1 = Status.PENDING;
Status s2 = Status.PENDING;
System.out.println(s1.equals(s2)); // true
System.out.println(s1 == s2); // also true (same object!)
hashCode: Consistent and Efficient
The inherited hashCode() method ensures enum constants work flawlessly in hash-based collections like HashMap and HashSet. You never have to worry about breaking the equals-hashCode contract—it's guaranteed by the Enum class.
Think of It Like This
Enums are like VIP citizens in Java's class system: they get a premium package of methods automatically implemented correctly, so you can focus on using them rather than maintaining them.
Key Takeaway: Enums extend Java's Enum class and inherit properly implemented toString(), equals(), and hashCode() methods automatically—making them safe, readable, and collection-friendly without any extra effort.