26

My question is related with System.in and System.out classes (there might be others like those in the Standard library). Why is that? Isn't that a bad practice in OOP? Shouldn't it be used like: System.getIn() and System.getOut()? I've always had this question and I hope I can find a good answer here.

Clawdidr
  • 363
  • 2
  • 8

4 Answers4

37

The definition for the in and out fields within the System class are:

public final static PrintStream out;
public final static InputStream in;

These are constants. They happen to be objects too, but they are constants. It is very much the same as the Math class:

public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;

Or in the Boolean class:

public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);

Or in the Color class:

public final static Color white     = new Color(255, 255, 255);
public final static Color black     = new Color(0, 0, 0);
public final static Color red       = new Color(255, 0, 0);

When accessing a public constant that doesn't change, there isn't a significant advantage to encapsulate it - conceptually or performance based. Its there. It isn't going to change.

There is no real difference between Color.white and System.out.

  • Well, I haven't seen it that way, they are constant objects. That's a pretty good explanation. – Clawdidr Aug 12 '13 at 15:30
  • 1
    @Clawdidr in today's Java, one *might* consider using the `enum` to hold them... though `enum` was new with Java 1.5 (not an option in the 1.0 days). –  Aug 12 '13 at 15:32
  • Just out of curiosity (not a Java developer myself): is there a difference between `final static` and `static final`? If so what is it? – Marjan Venema Aug 12 '13 at 17:28
  • 1
    @MarjanVenema no difference, just preferred order of the modifiers. [checkstyle modifier check](http://checkstyle.sourceforge.net/config_modifier.html) shows the preferred order. Apparently, whoever wrote those two source files in the jdk version I have didn't agree on the order. Its merely convention. –  Aug 12 '13 at 17:33
  • :) and thanks Michael, for taking the time to respond and for the link. – Marjan Venema Aug 12 '13 at 17:37
  • What a fantastic way to view it--constant objects. Never heard it that way before. Color me impressed. – Bill K Aug 12 '13 at 20:18
  • Actually, System.in/out/err are not constants. They are a special case ... `static final` variables that can be changed via special methods. – Stephen C Aug 13 '13 at 02:18
  • @StephenC yep, special native methods that dig into the VM itself. Within native methods, the java access control rules (final) are not enforced. Its mentioned in the [JLS](http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.4) Section 17.5.4. This still prevents silly the modification of it (`System.in = foo`) and also has checks against the SecrutiyManager. However, historically (1.0 - `setIn` was added in 1.1) and conceptually, `System.in` and its siblings are best thought of as constants. And given the 1.0 requirements of backwards compatibility, it can't be changed. –  Aug 13 '13 at 02:52
  • why are some upper case and some lower case? – jgauffin Aug 13 '13 at 06:15
  • @jgauffin poorly formalized standards when they were added? Color has both. The line after the `public final static Color white = new Color(255, 255, 255);` in my jdk is `public final static color WHITE = white;` –  Aug 13 '13 at 15:31
5

The real reason is that this is a legacy issue. The System.in,out,err constants were part of Java 1.0 ... and probably a lot further back. By the time it was clear that the design had problems, it was too late to fix it. The best they could do was to add the System.setIn,setOut,setErr methods in Java 1.1 and then deal with the language specification issues1.

This is similar to the issue of why there is a static System.arraycopy method whose name violates the Java naming conventions.


As to whether this is "bad design" or not, I think it is. There are situations where the current non-OO handling is a serious problem. (Think ... how can you run one Java program inside another when their "standard IO" stream requirements conflict. Think ... unit testing code that entails changing the streams.)

However, I can also relate to the argument that the current way of doing things is more convenient in a lot of cases.


1 - It is interesting to note that the System.in,out,err variables get special mention in the JLS as having "special semantics". The JLS says that if you change the value of a final field, the behaviour is undefined ... except in the case of these fields.

Stephen C
  • 25,180
  • 6
  • 64
  • 87
2

I believe the out object is immutable, which makes it somehow safe (this is debatable) for being kept in a public final static field.

Many of the classes in the JDK do not respect the best object-oriented design principles. One reason for this is the fact that they were written almost 20 years ago, when Object-Orientation was only emerging as a mainstream paradigm and many programmers simply were not familiar with them as they are now. A very good example of bad API design is the Date & Time API, which took them 19 years to change...

Random42
  • 10,370
  • 10
  • 48
  • 65
  • 3
    I'd make the statement even stronger, a public final variable (static or not) is exactly as "Safe" as a getter and I'd perfer the immutibility over a setter/getter pair. Setters are just about always a bad idea (Immutable is good--and if it can't be immutable the method that "Sets" it probably deserves a little business logic too), If you need a getter you might as well make it public final, but doing neither is preferable--don't ask a class for it's data, ask a class to do something to it's data. – Bill K Aug 12 '13 at 20:16
  • @BillK: Yes, also known as the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter) (though it's not a law, rather a guideline). – sleske Aug 13 '13 at 07:18
2

This answer is great and true.

I wanted to add that in some cases compromises were made for usability's sake.

Objects of type String can be instantiated without new, event when String is not a primitive:

String s = "Hello";

String being a non-primitive, should be instantiated like this:

String s = new String("Hello");          // this also works 

But the compiler allows for the shorter, less OO option, because String is by far the most widely used class in the API.

Also arrays can be initialized in a non-OO way:

int i[] = {1,2,3};

Weird enough, an object is either an instance of a class or an array. Meaning arrays are a completely separate type of class.

Arrays have a length public field which is not a constant. Also there's no documentation on the class arrays are an instance of. ( not to confuse with Arrays class or java.reflect.Array ).

int a = myArray.length;    // not length()
Tulains Córdova
  • 39,201
  • 12
  • 97
  • 154
  • 6
    Thee are different things - `new String("Hello")` will always create a new String object. While `String s = "Hello";` will use the interned object. Compare: `"Hello" == "Hello"` may be true, while `new String("Hello") == new String("Hello")` is always false. There is compile time optimization magic happening in the first that isn't possible with `new String("Hello")`. See http://en.wikipedia.org/wiki/String_interning –  Aug 12 '13 at 15:35
  • @MichaelT I added some extra wierdiness on arrays, just for completeness' sake. – Tulains Córdova Aug 12 '13 at 15:46
  • Yes, that's also true, the length field in arrays objects are public but not constants. – Clawdidr Aug 12 '13 at 16:08
  • @MichaelT: You're right but you say is not a valid reason to object to what the OP is talking about. – Tarik Aug 12 '13 at 17:10
  • 2
    @Tarik I was objecting to the "String being a non-primitive, should be instanciated like this: `String s = new String("Hello");`" which is incorrect. The shorter option (`String s = "Hello";`) is *more* correct because of string interning. –  Aug 12 '13 at 17:20
  • 2
    With `String`, there is no "more correct" option. Both are correct. Though, as MichaelT says, the shorter one is preferred because of String interning. – Andres F. Aug 12 '13 at 18:23
  • 1
    @AndresF. I changed "less correct" for "less OO". – Tulains Córdova Aug 12 '13 at 18:24
  • @user61852: A string literal passed to the `String` constructor must somehow yield a reference to a `String` object before the constructor can do anything with it, so how would assigning that reference to a variable be less OOP-ish than passing it as a constructor parameter? – supercat Jan 17 '14 at 00:16
  • @supercat I'm just talking syntax here. – Tulains Córdova Jan 17 '14 at 18:23