java difference between system.out.println() and println()

浪尽此生 提交于 2020-01-07 09:56:15

问题


I was wondering if there was a difference between these two e.g.

System.out.println("Hello World");

and

println("Hello World");

I know they print the same thing, but is there anything different? (I'm new to java, so I don't know so far)

In other words, does the "System.out" change anything?


回答1:


Yes, there is a difference, because they are not calling the same method.

Assuming the second statement actually compile, it means that the println("Hello World") call is for a method that is either:

  • defined in your class
  • inherited from a super class
  • a default method inherited from an interface (Java 8+)
  • statically imported1

Now, the local/inherited/imported println(String s) method could just have been implemented to call System.out.println(s), which would make it behave the same as the direct call to System.out.println(s), but that's different.


1) Since you cannot statically import java.lang.System.out.println() (it is not a static method), it would have to be statically imported from some other class.




回答2:


You might have a local method called println or a static import. So:

private void println(String str) {
    //
}

or

import static java.lang.System.out;

but then it'd have to be:

out.println("bla bla");

If you are using an IDE, try to open its declaration (F3 in Eclipse) and see where it takes you.



来源:https://stackoverflow.com/questions/37871663/java-difference-between-system-out-println-and-println

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