Creating Incompatible Number Subtypes

↘锁芯ラ 提交于 2019-12-06 08:21:55

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