Problem in System.out.println statement
Whenever we write开发者_JAVA百科 any statement to print to console in Java program:
System.out.print
or System.out.println
In above both statements we're calling out reference variable of PrintStream object without explicitly importing java.io package, so how we're accessing that object methods without resulting any compile time error?
The System object has references to java.io.PrintStream
objects embedded in it. So you don't need to explicitly import these - the runtime can derive this information unambiguously since it was embedded at compile-time.
As you've identified, if you used a PrintStream
object directly, you'd have to import that. The compilation stage doesn't know where to find it (it could search, but that could easily give ambiguous results).
Note also (in case there's any confusion), java.lang
is implicitly imported, hence you don't require an import statement for System
.
You only need to import class names for those that you wish to declare. So, for example:
PrintStream out = System.out;
would not compile unless you imported java.io.PrintStream
, but you can use the methods off of System.out, since it is "implicitly" imported at that point, since the compiler knows exactly what type System.out
is. In some languages, for example, Scala, you would not need to declare the type of the variable either, since it can be worked out via type inference.
Imports are syntactic sugar that allows you to avoid typing e.g. java.io.File file = new java.io.File("foo.txt")
every time but allow you to type File file = new File("foo.txt")
.
Nothing else.
So unless you have to create a new object or assign an object to a variable, and you want to avoid writing out the class name in full, you do not need to do any imports.
(in the above consider interfaces to be a class under cover)
精彩评论