Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Matt Avatar asked May 25 '26 07:05

Matt


1 Answers

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);
        }
    }
}
like image 179
corsiKa Avatar answered May 26 '26 21:05

corsiKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!