本文介绍了为什么shortValue()方法是具体的,但intValue()是抽象到java.lang.Number?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读 java.lang.Number 的源代码,我想知道为什么

I have read source code of java.lang.Number and I wondered why


  1. intValue()

  2. longValue()

  3. floatValue()

  4. doubleValue()

  1. intValue()
  2. longValue()
  3. floatValue()
  4. doubleValue()

是抽象的但是


  1. shortValue()

  2. byteValue()

  1. shortValue()
  2. byteValue()

具体。

源代码:

public abstract class Number implements java.io.Serializable {

      public abstract int intValue();

      public abstract long longValue();

      public abstract float floatValue();

      public abstract double doubleValue();

      public byte byteValue() {
        return (byte)intValue();
      }

     public short shortValue() {
        return (short)intValue();
      }

    private static final long serialVersionUID = -8742448824652078965L;
}

为什么java创始人已经这样做了?

Why java founders have made it so?

我没有看到这些方法之间存在很大差异。它似乎是相关的。

I don't see big differencies between these method. Its seem as related.

PS

来自Long class:

from Long class:

  public byte byteValue() {
        return (byte)value;
    }


    public short shortValue() {
        return (short)value;
    }


    public int intValue() {
        return (int)value;
    }


    public long longValue() {
        return (long)value;
    }


    public float floatValue() {
        return (float)value;
    }


    public double doubleValue() {
        return (double)value;
    }

来自Integer类

public byte byteValue() {
        return (byte)value;
    }


    public short shortValue() {
        return (short)value;
    }


    public int intValue() {
        return value;
    }


    public long longValue() {
        return (long)value;
    }


    public float floatValue() {
        return (float)value;
    }

    public double doubleValue() {
        return (double)value;
    }

因此我们看到很多相同的代码。我认为复制粘贴开发很糟糕,但我认为Java创始人有理由这样做。

Hence we are see a lot of same code. I think copy paste development is bad but I think that Java founders have reasons for this.

推荐答案

根据,方法 byteValue shortValue 首先在JDK1.1中添加。这与第一个JDK版本中已有的其他Value方法不同。
我的假设是这两种方法是具体的,以保持与 Number 的现有(也是非标准)子类的兼容性,否则这些子类将被破坏通过在超类中添加新的抽象方法。

According to the documentation of the Number class, the methods byteValue and shortValue were added first in JDK1.1. This is unlike the other "Value" methods which were already available in the very first JDK release.My assumption is that those two methods were made concrete in order to keep compatibility with existing (also non-standard) subclasses of Number, which would otherwise have been broken by the addition of new abstract methods in the superclass.

这篇关于为什么shortValue()方法是具体的,但intValue()是抽象到java.lang.Number?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:01