Search code examples
javafinal

Resetting System.in/out


If System.out and System.in are made final so that we do not change them, then why do we have the methods System.setIn and System.setOut? Isn't the following statement contradictory?

System.in and System.out are accessible directly without accessor methods. But they are not directly redirectable to other streams because they are final. But we do have setter methods to set them to some other streams.

If they are final why even let them be reset? Or if we need them to be able to reset to some other streams why have them final in first place? Instead of directly accessing them why not let users write System.getIn() and System.getOut()?


Solution

  • You're basically looking at design warts left over from the very early days of Java. The fields existed in Java 1.0 (presumably already public and final), and when the designers realized that they needed a way to redirect them it was too late to change because that would have broken pretty much every single Java program in existence.

    Java's design has always valued downwards compatibility above all else, so in Java 1.1 they added the set methods as workaround instead (making the fields non-final would just have made the design flaw worse, at least this way the set methods can e.g. do a permissions check).