java - Number 类中的抽象方法

标签 java class numbers abstract

为什么Number类提供了Double、Int、Long、Float的转换方法的抽象方法,而没有提供byte、short的抽象方法?

总的来说,我对何时使用抽象方法有点困惑,因为我刚刚开始学习 Java。

感谢任何人提供的任何见解。

最佳答案

一看他们的来源就知道为什么:

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

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

它们都依赖于 intValue() 将被定义的事实,并且只使用它们为此提供的任何东西。

这让我想知道为什么他们不做

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

因为同样的规则适用。

请注意,没有任何内容表明您无论如何都不能覆盖这些方法。它们不必是抽象的,您就可以覆盖它们。

我机器上的结果:

C:\Documents and Settings\glow\My Documents>java SizeTest
int: 45069467
short: 45069467
byte: 90443706
long: 11303499

C:\Documents and Settings\glow\My Documents>

类:

class SizeTest {

    /**
     * For each primitive type int, short, byte and long,
     * attempt to make an array as large as you can until
     * running out of memory. Start with an array of 10000,
     * and increase capacity by 1% until it throws an error.
     * Catch the error and print the size.
     */    
    public static void main(String[] args) {
        int len = 10000;
        final double inc = 1.01;
        try {
            while(true) {
                len = (int)(len * inc);
                int[] arr = new int[len];
            }
        } catch(Throwable t) {
            System.out.println("int: " + len);
        }

        len = 10000;
        try {
            while(true) {
                len = (int)(len * inc);
                short[] arr = new short[len];
            }
        } catch(Throwable t) {
            System.out.println("short: " + len);
        }


        len = 10000;
        try {
            while(true) {
                len = (int)(len * inc);
                byte[] arr = new byte[len];
            }
        } catch(Throwable t) {
            System.out.println("byte: " + len);
        }

        len = 10000;
        try {
            while(true) {
                len = (int)(len * inc);
                long[] arr = new long[len];
            }
        } catch(Throwable t) {
            System.out.println("long: " + len);
        }
    }
}

关于java - Number 类中的抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707448/

相关文章:

java - 我正在尝试将 JPanel 插入 JFrame 但 JPanel 不显示

如果数字超过 1000,Angular2+ 货币管道将不起作用

java - 如何使用 Java 解析 midi 的速度?

java - 为什么在 Java 中比较 Integer 和 int 会抛出 NullPointerException?

c++ - 如何实例化一个只知道其名称的对象?

python - Python代码在一个编辑器中工作,而不在另一个编辑器中工作

java - 用数字作为单词比较两个字符串

java - NoClassDefFound错误: org/glassfish/jersey/process/internal/RequestExecutorFactory

java - Struts forEach 标签不遍历 ArrayList

c++ - 在 C++ 的 python 类中指定静态变量