Abstract methods in a class of numbers

Why does the Number class provide abstract methods for conversion methods for Double, Int, Long, and Float, but not abstract methods for bytes and short?

In general, I got a little confused about when to use abstract methods, since I was just starting to learn Java.

Thanks for any insights anyone can offer.

+3
java class numbers abstract
source share
1 answer

One glance at the source for them says why:

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

Both of them rely on intValue() be defined and just use what they provide for this.

It makes me wonder why they don’t just do

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

Because the same rule applies.

Note that nothing says that you cannot override these methods anyway. They should not be abstract so that you can redefine 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> 

Grade:

 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); } } } 
+4
source share

All Articles