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).
In Java 1.0.x System.out
and friends were not final
—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, out
was made final and written to with a native method, which was wrapped with the appropriate security checks.
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 for final
and setOut()
, 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 the out
member 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.
This has similarities with Array.length
vs List.size()
.
Could it have been done for historical reasons? Are there any other languages like this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With