Java out.println() how is this possible?

五迷三道 提交于 2019-11-27 01:19:02

问题


I've seen some code such as:

out.println("print something");

I tried import java.lang.System;

but it's not working. How do you use out.println() ?


回答1:


static imports do the trick:

import static java.lang.System.out;

or alternatively import every static method and field using

import static java.lang.System.*;

Addendum by @Steve C: note that @sfussenegger said this in a comment on my Answer.

"Using such a static import of System.out isn't suited for more than simple run-once code."

So please don't imagine that he (or I) think that this solution is Good Practice.




回答2:


PrintStream out = System.out;
out.println( "hello" );



回答3:


@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.




回答4:


Well, you would typically use

System.out.println("print something");

which doesn't require any imports. However, since out is a static field inside of System, you could write use a static import like this:

import static java.lang.System.*;

class Test {
    public static void main(String[] args) {
        out.println("print something");
    }
}

Take a look at this link. Typically you would only do this if you are using a lot of static methods from a particular class, like I use it all the time for junit asserts, and easymock.




回答5:


out is a PrintStream type of static variable(object) of System class and println() is function of the PrintStream class.

class PrintStream
{
    public void println(){}    //member function
    ...
}

class System
{
    public static final PrintStream out;   //data member
    ...
}

That is why the static variable(object) out is accessed with the class name System which further invokes the method println() of it's type PrintStream (which is a class).




回答6:


You will have to create an object out first. More about this here:

    // write to stdout
    out = System.out;
    out.println("Test 1");
    out.close();



回答7:


you can see this also in sockets ...

PrintWriter out = new PrintWriter(socket.getOutputStream());

out.println("hello");



回答8:


simply import :

import static java.lang.System.*;



回答9:


Or simply:

System.out.println("Some text");


来源:https://stackoverflow.com/questions/2504078/java-out-println-how-is-this-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!