[英]Instantiating an object by chaining constructors
My textbook has an example in the Files and Streams section that confuses me. 我的教科书在“文件和流”部分中有一个使我感到困惑的示例。
BufferedReader inFile = new BufferedReader (new FileReader ("data.txt"));
My thinking is we are creating an object, of type BufferedReader
and constructing them with another classes constructor FileReader
and then 'laying' that object into the BufferedReader
constructor. 我的想法是,我们正在创建一个
BufferedReader
类型的对象,并使用另一个类构造函数FileReader
构造它们,然后将该对象“放置”到BufferedReader
构造函数中。
Why are we instantiating the object with two 'new' keywords and what is happening? 为什么我们用两个'new'关键字实例化对象,这是怎么回事?
Does this fall under polymorphism or inheritism? 这属于多态还是继承?
Perhaps this equivalent code will make more sense: 也许下面的等效代码更有意义:
FileReader fileReader = new FileReader("data.txt");
BufferedReader inFile = new BufferedReader(fileReader);
All this does is construct a FileReader
object that is used as an argument for the BufferedReader
constructor. 所有这一切都是构造一个
FileReader
对象,该对象用作BufferedReader
构造函数的参数。 This is an example of neither polymorphism or inheritance, this is just nesting expressions inside other expressions. 这既不是多态也不是继承的示例,这只是将表达式嵌套在其他表达式中。
Most stream classes can be chained together. 大多数流类可以链接在一起。 The new operator returns an instance of the type following, using the constructor that follows.
new运算符使用以下构造函数返回以下类型的实例。 So the
FileReader
is initialized with a file that will be read, with the resulting object passed to a BufferedReader
such that the read from the file will be buffered for efficient I/O during the actual read. 因此,使用将要读取的文件初始化
FileReader
,并将生成的对象传递给BufferedReader
,以便在实际读取期间对文件的读取进行缓冲,以进行有效的I / O。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.