Pages

9 Apr 2015

Java Enum's mystery

Today, I accidentally took a look at toMillis(long d) method of Java's TimeUnit class:

https://android.googlesource.com/platform/libcore/+/refs/heads/master/luni/src/main/java/java/util/concurrent/TimeUnit.java

And I was like: "such class, very confusing, much questions, wow" lol

Why this class has toMillis(long d) method, and its enum elements have that method as well?
Why this class's toMillis(long d) has only this line in its implementation?

throw new AbstractMethodError();

It was so confusing because normally I mostly only use enum as cases for switch statements, so I tried to research for a while then I occurred this thread: http://stackoverflow.com/questions/18392885/java-definition-of-methods-and-variables-inside-enums-constant.

Still confusing but somehow I came to this conclusion:
  • Basically we can use Enum as a class to hold constants of a certain type that has certain desired methods OR we can call it "constant method" (I doubt about the latter?!)
  • TimeUnit's toMillis(long d) method basically just throws an exception (AbstractMethodError), and its elements (SECONDS, MINUTES...) have type is TimeUnit, so they just override TimeUnit's toMillis(long d) method (@Override is omitted in this class, I guess the author did it intentionally because he didn't call super method in any overridden methods, and that was the point made this class so confusing at first to me). Then when we call TimeUnit.SECONDS.toMillis(10), SECONDS's toMillis(long d) will be called but it doesn't throw any exceptions because super method wasn't called.
That's it!
The method looks so well-designed but kind of confusing at first.
Now I see it's a really good practice to use Java's Enum.

No comments:

Post a Comment