2

In Ada, it is possible to create incompatible equivalent numeric types:

type Integer_1 is range 1 .. 10;
type Integer_2 is range 1 .. 10;
A : Integer_1 := 8;
B : Integer_2 := A; -- illegal!

This prevents accidental logical errors such as adding a temperature to a distance.

Is it possible to do something similar in Java? E.g.

class Temperature extends Double {}
class Distance extends Double {}
Temperature temp = 20.0;
Distance distance = temp; // Illegal!

EDIT

I've discovered an unrelated question with a related answer. This uses annotations and a special processor on compile to issue warnings when such assignments occur. It seems like the most painless way to do this - no need for special classes with the development and execution penalties those would incur.

Avi Chapman
  • 319
  • 1
  • 8

1 Answers1

4

It's not common to wrap objects for the reason you specified in Java. But it is possible.

Rather than using extends Double (which doesn't work because Double is final). You can instead use delegation.

public class Distance {
    private double distance;
    // constructor, getter, setter
}

public class Temperature {
    private double temp;
    // constructor, getter, setter
}

Then the following will generate a compile-time error.

Temperature temp = new Temperature(20.0);
Distance distance = temp; // Illegal!
J.A.P
  • 715
  • 6
  • 13