3
爲什麼Number類爲Double,Int,Long和Float提供了轉換方法的抽象方法,但是不提供字節和短方法的抽象方法?編號分類中的抽象方法
總的來說,我對使用抽象方法的時候略有困惑,因爲我剛開始學習Java。
感謝任何人都可以提供的見解。從源頭上爲他們
爲什麼Number類爲Double,Int,Long和Float提供了轉換方法的抽象方法,但是不提供字節和短方法的抽象方法?編號分類中的抽象方法
總的來說,我對使用抽象方法的時候略有困惑,因爲我剛開始學習Java。
感謝任何人都可以提供的見解。從源頭上爲他們
一看說爲什麼:
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);
}
}
}
謝謝,這有助於。這可能是一個愚蠢的問題,但您究竟如何看待Java API的源代碼? – Matt 2011-04-18 19:05:49
Number類可以追溯到Java 1.1,所以我不會認爲他們對他們想要的東西有非常清楚的概念。但請記住,在Java中,long和int的行爲不同,而字節,shorts仍然在32位空間中處理。 – 2011-04-18 19:10:01
@Kevin,re:Java源代碼 - 我是使用jdocs.com的粉絲。例如,http://www.jdocs.com/harmony/5.M5/java/lang/Number.html – 2011-04-18 19:16:51