I am just now learning about composition. Would Scanner(System.in) be considered an example of composition?
Asked
Active
Viewed 71 times
-1
-
1http://stackoverflow.com/questions/2399544/difference-between-inheritance-and-composition – Jake Miller Aug 03 '16 at 14:04
1 Answers
0
Yes, it is.
The point is that Scanner
has a "something" that it can read data from, and it knows how to process that data into tokens.
That "something" can be standard input, a file, a string etc; but there isn't a separate subclass for reading from each of these these things. Indeed, you can't extend Scanner
, as it is final
.
What you might find interesting about new Scanner(System.in)
is that the Scanner
doesn't keep hold of System.in
directly: if you look at the constructor's source code, you will see:
public Scanner(InputStream source) {
this(new InputStreamReader(source),
WHITESPACE_PATTERN);
}
private Scanner(Readable source, Pattern pattern) {
// ...
this.source = source;
// ...
}
source
(e.g. System.in
) is wrapped in an InputStreamReader
, and it is that which is held onto by the Scanner
. So you've got two levels of composition:
Scanner
has aReadable
(theInputStreamReader
);- The
InputStreamReader
has anInputStream
(e.g.System.in
).

Andy Turner
- 137,514
- 11
- 162
- 243