创建不兼容的数字子类型 [英] Creating Incompatible Number Subtypes

查看:71
本文介绍了创建不兼容的数字子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ada中,可以创建不兼容的等效数值类型:

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.

是否可以在Java中做类似的事情?例如,

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!

编辑

我发现了无关的问题,并给出了相关的答案。当分配发生时,它使用注释和编译时的特殊处理器来发出警告。看来这是最轻松的方法-不需要特殊的类,因为它们会产生开发和执行上的惩罚。

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.

推荐答案

由于您在Java中指定的原因,包装对象并不常见。

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

而不是使用扩展Double (由于 Double 是最终的)。

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
}

然后将生成以下内容

Temperature temp = new Temperature(20.0);
Distance distance = temp; // Illegal!

这篇关于创建不兼容的数字子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆