Number类中的抽象方法 [英] Abstract Methods in Number Class

查看:30
本文介绍了Number类中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is it that the Number Class provides abstract methods for conversion methods for Double, Int, Long, and Float but not abstract methods for byte and short?

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

Overall I am slightly confused on when to use Abstract methods, as I just began learning Java.

感谢任何人可以提供的任何见解.

Thanks for any insight anyone can offer.

推荐答案

一看源码就知道为什么:

One look at the source for them says why:

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

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

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

They both rely on the fact that intValue() will be defined, and just use whatever they provide for that.

这让我想知道为什么他们不直接制作

This makes me wonder why they don't just make

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

因为同样的规则适用.

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

Note that there's nothing that says you can't override these methods anyway. They don't have to be abstract for you to override them.

我机器上的结果:

C:Documents and SettingsglowMy Documents>java SizeTest
int: 45069467
short: 45069467
byte: 90443706
long: 11303499

C:Documents and SettingsglowMy 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);
        }
    }
}

这篇关于Number类中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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