0

I have searched the web for information, and I got many answers about how enums are implemented. Consider this enum type:

public class Days{

public static final Days MONDAY = new Days(); 
public static final Days TUESDAY = new Days(); 

}

Is it true that that is equivalent to this:

public enum Days1{

MONDAY,TUESDAY;

}

?

If I print these in my main method as:

System.out.println(Days.MONDAY);
System.out.println(Days1.MONDAY);

, the two yield different results. Why? How is it that enum constants get printed as they are created, but references to other objects cannot be printed as they are?

John Bollinger
  • 160,171
  • 8
  • 81
  • 157

3 Answers3

1

It is true that your class Days is similar to your enum Days1. Both implement the typesafe enum pattern, providing the same names for the enumerated values.

But they are not equivalent (nor "equal", as the original wording put it). Bona fide Java enums, such as your Days1, get a lot of additional structure and scaffolding, much of it from subclassing java.lang.Enum, and some just synthesized by the compiler. Among these is Enum's toString() method, which is responsible for your System.out.println(Days1.MONDAY); outputting the enum name instead of a cryptic string.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

Just to explain the background, Java originally had no enum type, so programmers developed the enum pattern using classes, as your first example. The flexibility of using classes rather than ints as was the practice for most languages at the time inspired the design of Java enums when they were eventually added in Java 5 (and also in later languages, like Rust).

John Bayko
  • 746
  • 4
  • 7
0

To strictly answer your question: see source of toString() method of java.lang.Enum type. You'll find it returns the name() of particular enum constant. Your handmade enum constant does not override toString() method so you see default implementation from java.lang.Object.

You are generally right though - the Java enum implements typesafe enum pattern which basically does what you implemented using constants. See the chapter in Effective Java.

Tomáš Záluský
  • 10,735
  • 2
  • 36
  • 64
  • what if i use constants in case ? if constants have no value then how switch differentiate between its cases – Will Hunting Oct 28 '20 at 16:58
  • You cannot use your `Days` "constants" in switch statement since only types according to JLS https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11 are allowed. You can use `Days1` enum constants. Java effectively translates enum to class with constants and furthermore adds another value such as `toString()`, ability to be used in `switch` any many other features, which is baked into language and prevents you typing boring lengthy things again and again. – Tomáš Záluský Oct 28 '20 at 19:47