简体   繁体   中英

why java.io.PrintStream is not needed in System.out.println()?

So I ask myself why I don't have to import java.io.PrintStream to use System.out . I know that java.lang is imported by default by the compiler. Allright.

Because System is a class of java.lang I can use the field System.out . But this field has the type java.io.PrintStream and this class is not imported by default (it's in the java.io package), so why can i access System.out.print() for instance without importing java.io.PrintStream separately ?

If I create my own class MyClass then I cannot do something like this MyClass anInstance = new MyClass(); MyClass need first to be imported. Why is this not mandatory for the PrintStream ?

Thanks in advance.

You would only need to import PrintStream if you needed to use PrintStream (the class name) in your code. Using a field on another object which is of type PrintStream doesn't require it.

That is, import is to tell the compiler what PrintStream (the literal text) means in your code. It's not to tell the compiler that you'll use a PrintStream object you get from somewhere else (in this case, System ).

Put it another way: import is about knowing how to compile the source text; it's not about what gets used at runtime. Imports are not written to class files, for instance; the information just isn't needed at runtime. Field and variable definitions are stored with their fully-qualified class names, not import -relative ones. Since out 's type information in System says it's java.io.PrintStream , the compiler (and later, the JVM) knows it's a java.io.PrintStream , whether you import PrintStream in your code or not.

X.java

package p;
import q.Y;
public class X { Y y; }

Z.java

import p.X;

... X x = ...;
... x.y ...;

For the occurrence of X the compiler needs the import of X.

For xy the compiler can find in the class data of X the class Y for having the methods of Y and such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM