System.in属于哪个输入类,为什么? [英] What input class does System.in belongs to and why?
问题描述
代码
import java.io.*;
class ioTest1{
public static void main(String args[]){
System.out.println(System.in.getClass());
}
}
返回 System.in
属于 BufferedInputStream
类。为什么会这样?
returns that System.in
belongs to the BufferedInputStream
class. Why is that?
因为类系统
定义 System.in
要 InputStream
,我可以看到结果并非不可能。但是为什么以前的代码不能返回从 InputStream
继承的另一个类,例如 DataInputStream
?
Since class System
defines System.in
to be InputStream
, I can see how the result isn't impossible. But why can't the previous code return another class inherited from InputStream
,like for example DataInputStream
?
推荐答案
正如评论中所解释的那样,没有什么可以阻止 System.in
来自是 DataInputStream
,但鉴于 BufferedInputStream
是一个简单的 InputStream
包括缓冲数据(总是一个好主意),给出最通用的类型更有意义。
As explained in the comments, there's nothing that would have prevented System.in
from being DataInputStream
, but given that BufferedInputStream
is a no-frills InputStream
that includes buffering of data (always a good idea), it makes more sense to give the most generic type possible.
然后开发人员可以用缓冲流包装例如a DataInputStream
如果程序是通过管道二进制数据提供的,或者是 InputStreamReader
如果程序正在接收文本数据用户。
Developers can then wrap the buffered stream with for example a DataInputStream
if the program is fed piped binary data, or an InputStreamReader
if the program is receiving text data from the user.
System.in
是一个 BufferedInputStream
因为它不需要任何其他东西。
System.in
is a BufferedInputStream
because it doesn't need to be anything else.
这篇关于System.in属于哪个输入类,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!