3

I took a look into TimeUnit and toMillis() method.

 public long toMillis(long paramLong)
 {
    throw new AbstractMethodError();
 }

toMillis() method do nothing other than throw an AbstractMethodError exception.

So, How does toMillis() method convert seconds, minutes, etc to milliseconds?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Tran Thien Chien
  • 643
  • 2
  • 6
  • 17
  • TimeUnit is basically the abstract prototype. You need to look into concrete `TimeUnits`, such as `TimeUnit.SECONDS` – rethab Oct 05 '16 at 05:19

3 Answers3

7

Each value within TimeUnit overrides it, basically. You never end up calling that implementation, because you never have a reference to an object of type TimeUnit - it's always a subclass representing one of the values.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Open the TimeUnit and look the constants inside...

/**
 * Time unit representing one thousandth of a microsecond
 */
NANOSECONDS {
    public long toNanos(long d)   { return d; }
    public long toMicros(long d)  { return d/(C1/C0); }
    public long toMillis(long d)  { return d/(C2/C0); }
    public long toSeconds(long d) { return d/(C3/C0); }
    public long toMinutes(long d) { return d/(C4/C0); }
    public long toHours(long d)   { return d/(C5/C0); }
    public long toDays(long d)    { return d/(C6/C0); }
    public long convert(long d, TimeUnit u) { return u.toNanos(d); }
    int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
},

/**
 * Time unit representing one thousandth of a millisecond
 */
MICROSECONDS {
    public long toNanos(long d)   { return x(d, C1/C0, MAX/(C1/C0)); }
    public long toMicros(long d)  { return d; }
    public long toMillis(long d)  { return d/(C2/C1); }
    public long toSeconds(long d) { return d/(C3/C1); }
    public long toMinutes(long d) { return d/(C4/C1); }
    public long toHours(long d)   { return d/(C5/C1); }
    public long toDays(long d)    { return d/(C6/C1); }
    public long convert(long d, TimeUnit u) { return u.toMicros(d); }
    int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
},

as you will see, every constant in the enumerator TimeUnit NANOSECONDS, MICROSECONDS etc implements anonymously methods that give you indirect access to toMillis() therefore this method

 public long toMillis(long duration) {
        throw new AbstractMethodError();
    }

is never accessed by your code directly...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • I saw the override methods in JDK but when I used decompiler to decompile 'TimeUnit' from JRE. The override methods are not there. Why does it happens? – Tran Thien Chien Oct 05 '16 at 04:49
2

It's method override.

You can see the overrided implementations in NANOSECONDS, MICROSECONDS and etc.

Henry
  • 136
  • 3