Has anyone got an idea regarding the motivation behind the awkward design of the java.lang.System.out?
Awkwardness:
First, the out member is exposed (Encapsulation anyone?).
Second, it is final but can be changed via setOut() (contradicts final).
-
I would bet it is exposed mainly for brevity. Compare:
System.out.prinln("blah");with
System.getOut().println("blah");The former is not many character shorter, but still it is shorter, and simpler conceptually. It is also very probably faster, perhaps especially back in the day when JIT was not too common in Java virtual machines; I bet the direct access is faster than a method call in those cases. So, it boils down to being a tradeoff.
UPDATE:
As forfinalandsetOut(), the documentation for the latter says that if there is a security manager, it will be queried to see if the caller is allowed to re-set the output stream. This might be the answer; if theoutmember had been directly assignable, there would not have been a way to protect it.This is just my interpretation of the API and the thoughts that might be behind its design, I could be off.
Shimi Bandiel : Ok, so why final & setOut()Hemal Pandya : Why is the choice between System.out.println and System.outOut().println? Why not StdIo.printLn?Thorbjørn Ravn Andersen : @Hermal, because Java was created by a Unix-company, and in/out/err are standard Unix concepts. -
This has similarities with
Array.lengthvsList.size().Could it have been done for historical reasons? Are there any other languages like this?
Shimi Bandiel : although you can't use setLength() on an array.Esko : I think Array.length is the way it is because someone originally wanted to highlight that arrays aren't objects (unless encapsulated of course). Other than that I agree, File.mkdir(); anyone? :)Carlos Heuberger : but arrays ARE objects, just a "strange" notation (Object obj = new int[4];)TofuBeer : Arrays are Objects: http://java.sun.com/docs/books/jls/third_edition/html/arrays.html "In the Java programming language arrays are objects..." -
In Java 1.0.x
System.outand friends were notfinal—it was possible to change them by assigning directly to them. However, this presented an issue when Sun decided to optionally restrict this behavior in Java 1.1 (for applets, at the time). To maintain at least some backwards compatibility,outwas made final and written to with a native method, which was wrapped with the appropriate security checks.Tom Hawtin - tackline : And there had to be a specific exception for System.in/out/err for the new Java Memory Model.
0 comments:
Post a Comment