Creating Incompatible Number Subtypes

萝らか妹 提交于 2019-12-10 11:22:52

问题


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.


回答1:


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!


来源:https://stackoverflow.com/questions/53715411/creating-incompatible-number-subtypes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!