2011-04-18 35 views
3

为什么Number类为Double,Int,Long和Float提供了转换方法的抽象方法,但是不提供字节和短方法的抽象方法?编号分类中的抽象方法

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

感谢任何人都可以提供的见解。从源头上为他们

回答

4

一看说为什么:

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

谢谢,这有助于。这可能是一个愚蠢的问题,但您究竟如何看待Java API的源代码? – Matt 2011-04-18 19:05:49

+0

Number类可以追溯到Java 1.1,所以我不会认为他们对他们想要的东西有非常清楚的概念。但请记住,在Java中,long和int的行为不同,而字节,shorts仍然在32位空间中处理。 – 2011-04-18 19:10:01

+0

@Kevin,re:Java源代码 - 我是使用jdocs.com的粉丝。例如,http://www.jdocs.com/harmony/5.M5/java/lang/Number.html – 2011-04-18 19:16:51