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.
|
||||
|
The definition for the
These are constants. They happen to be objects too, but they are constants. It is very much the same as the Math class:
Or in the Boolean class:
Or in the Color class:
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 | |||||||||||||||||||||
|
The real reason is that this is a legacy issue. The This is similar to the issue of why there is a static 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 | ||||
|
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... | |||||||||
|
MichaelT's 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 being a non-primitive, should be instanciated like this:
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:
Wierd 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
| |||||||||||||||||||||
|