Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a unit converter in java

How could I possibly implement a unit converter in Java??? I was thinking of having a abstract base class:

public abstract class Unit {
    ...
    public void convertTo(Unit unit);
}

Then having each class like Meter Kilometer Inch Centimeter Millimeter ... derive from that base Unit class. All the units of length would be in a package called com.unitconverter.distance, then a package, com.unitconverter.energy, for energy etc. etc. So is this the best way to implement a unit converter? Or is there a better or more easier way?

like image 339
Mohit Deshpande Avatar asked May 21 '10 23:05

Mohit Deshpande


2 Answers

There's been a fair amount of work on this, including JSR 108 (withdrawn) and JSR-275 (rejected). See JScience and UnitsOfMeasure implementations of the latter

like image 81
Matthew Flaschen Avatar answered Oct 14 '22 08:10

Matthew Flaschen


You should check how java.util.concurrent.TimeUnit is implemented, just as a reference. This is an enum that supports the convert(..) operation.

like image 26
Eyal Schneider Avatar answered Oct 14 '22 09:10

Eyal Schneider