为什么Number类提供了Double、Int、Long、Float的转换方法的抽象方法,而没有提供byte、short的抽象方法?
总的来说,我对何时使用抽象方法有点困惑,因为我刚刚开始学习 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 - Number 类中的抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707448/