At one point, I needed to convert between different units. These might be units of weight, volume, length, etc. I created a bunch of enums, i.e.,
I then created a Convert class and overloaded the methods based on the enum, i.e.,
I then called convert( type, value ) wherever I needed to do the conversion.
I am now finding I am writing a lot of custom text fields, one for each class of enum. I was hoping that since all the functions except convert are the same and convert is overloaded, I might be able to extend a generic class. I haven't been able to get that to work.
If I try something like:
I can create an interface (see below), but most of the code in the custom text fields is identical (everything but the calls to Convert). Is there a way to extend a class when I have a set of overloaded functions like above? Or a better implementation than just an interface, so I don't duplicate so much code?
In your Java installation folder, there is a file called src.zip. Unzip it, and explore it till you find the TimeUnit enum. Inspect its convert method. If you click on the word TimeUnit, you can work out from the API documentation it is in the concurrent folder in the util folder in the java folder. that has methods allowing you to convert times from milliseconds to hours, etc. Is that the sort of thing you are looking for here, converting feet to metres or pounds to kilograms? Can you use similar techniques?
Jon Swanson wrote:I can create an interface (see below), but most of the code in the custom text fields is identical (everything but the calls to Convert). Is there a way to extend a class when I have a set of overloaded functions like above? Or a better implementation than just an interface, so I don't duplicate so much code?
I hate to say, but you were on the right lines at the start with your enums; you just didn't take it a stage further and link it properly with your other good idea: the interface. And now you've started overthinking...
Go back to your Weight enum (BTW, don't use all-caps for class names). Why not just add a convertTo() method and a little "knowledge" to it?
Then it might look something like:and now
Weight.KILOGRAMS.convertTo(Weight.POUNDS, 3.0) will return
And now you can take it a stage further. Enums can implement interfaces, so what about:and then, your Weight definition becomes:HIH
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Joined: Oct 13, 2005
That looks very similar to TimeUnit, only in TimeUnit the numbers include 1000 1000000 1000000000 etc.
Joined: Oct 10, 2011
Thanks all, I could tell I was going about it wrong. The example was really helpful.
Joined: Oct 13, 2005
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: A more effcient way to work with overloaded functions with enums as arguments than an interface?