为什么Number Class为Double,Int,Long和Float的转换方法提供抽象方法,而不为字节和short提供抽象方法?
总体而言,我对何时使用抽象方法感到有些困惑,因为我刚开始学习Java。
感谢任何人提供的任何见解。
答案 0 :(得分: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);
}
}
}