[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 180
  • Last Modified:

Make a class autobox & autounbox?

I see the Double class has autoboxing and unboxing, so I can do things like:
Double a = new Double(1.0);
Double b = new Double(2.0);
If (a < b) {
...
}

Open in new window

Can I make my own data class that behaves the same way? Say I have a variable celsius, and celsius is an immutable instance of a Double, but it's a special kind of Double, it's a double that represents a Celsius temperature reading, so I would like to create a class Celsius, which is a Double, so I can do:
Celsius c = new Celcius(23.0);
Celsius d = new Celsius(24.0);
If (c < d) {
...
}

Open in new window

But Java doesn't have operator overloading, and Double is a final class, so I can't extend it. Is there another way?
0
deleyd
Asked:
deleyd
  • 2
2 Solutions
 
CEHJCommented:
Say I have a variable celsius, and celsius is an immutable instance of a Double
But it isn't. Double is final, so it can't be. What you mean is that you've initialized a custom class Celsius with a double. Boxing is only concerned with primitives, so is not relevant to your case.
0
 
deleydAuthor Commented:
Yea that's my problem. Can I get my class Celsius to do the same thing the class Double does, so I can compare them using simple = < > instead of the cumbersome:
if(myCelsiusValue.compareTo(anotherCelsiusValue) > 0) {
...

Open in new window

Instead I'd like to be able to:
if(myCelsiusValue > anotherCelsiusValue) {
...

Open in new window

But I'd also like the Celsius variable to be a Celsius variable so I can also do:
public void myMethod(Celsius value) {
...

Open in new window

That way I can ensure the value being pass is a Celsius value and not just any Double.  e.g. it's not a Fahrenheit variable.
0
 
Jeffrey Dake Senior Director of TechnologyCommented:
You wouldn't be able to use the autoboxing and the < format, but you could make your class implement comparable and then do something like.

If (a.compareTo(b) < 0) 
{
}

Open in new window


http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo%28T%29

Like CEHJ said, the autoboxing is really only for primitives, so you will need to use function calls for your case.
0
 
CEHJCommented:
but you could make your class implement comparable
Yes, that's the best you can do
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now