Michael Bishara
Michael Bishara

Reputation: 41

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.

Why are we instantiating the object with two 'new' keywords and what is happening?

Does this fall under polymorphism or inheritism?

Upvotes: 0

Views: 45

Answers (2)

particleman
particleman

Reputation: 645

Most stream classes can be chained together. The new operator returns an instance of the type following, using the constructor that follows. 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.

Upvotes: 1

k_ssb
k_ssb

Reputation: 6252

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. This is an example of neither polymorphism or inheritance, this is just nesting expressions inside other expressions.

Upvotes: 1

Related Questions