简体   繁体   中英

Abstract Methods in Number Class

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?

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();
}

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();
}

Since the same rule applies.

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.

Results on my machine:

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:

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM