Burt Reynolds Burt Reynolds - 1 year ago 65
Java Question

Is Scanner(System.in) considered an example of composition

I am just now learning about composition. Would Scanner(System.in) be considered an example of composition?

Answer Source

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),    

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 a Readable (the InputStreamReader);
  • The InputStreamReader has an InputStream (e.g. System.in).