各位麻油們,大家學(xué)了這么久Java了,確定真的掌握了System.out.println(); 嗎?確定了解了Java面向?qū)ο缶幊痰暮x了嗎?今天,我就深層刨析一下這串源代碼!
如果能自己讀懂System.out.println(),就真正了解了Java面向?qū)ο缶幊痰暮x,面向?qū)ο缶幊碳磩?chuàng)建了對象,所有的事情讓對象幫親力親為(即對象調(diào)用方法)
System.out.println("hello world");
hello world
Process finished with exit code 0
話不多說,首先對System源碼進行分析:
System就是java中的一個類
out源碼分析:
1.out是System里面的一個靜態(tài)數(shù)據(jù)成員,而且這個成員是java.io.PrintStream類的引用
2.out已經(jīng)存在了并且用static修飾了,所以可以直接使用類名+屬性名的方式調(diào)用,也就是System.out。
3.out的真實類型是一個靜態(tài)的PrintStream對象,靜態(tài)的所以不需要創(chuàng)建對象。
println源碼分析:
1.println()就是java.io.PrintStream類里的一個方法,它的作用是向控制臺輸出信息。
public void println(String x) {
? ? ? ? if (getClass() == PrintStream.class) {
? ? ? ? ? ? writeln(String.valueOf(x));
? ? ? ? } else {
? ? ? ? ? ? synchronized (this) {
? ? ? ? ? ? ? ? print(x);
? ? ? ? ? ? ? ? newLine();
? ? ? ? ? ? }
? ? ? ? }
? ? }
2.之所以可以輸出任何東西,是因為里面有方法重載!!
public void println(int x) {
? ? ? ? if (getClass() == PrintStream.class) {
? ? ? ? ? ? writeln(String.valueOf(x));
? ? ? ? } else {
? ? ? ? ? ? synchronized (this) {
? ? ? ? ? ? ? ? print(x);
? ? ? ? ? ? ? ? newLine();
? ? ? ? ? ? }
? ? ? ? }
? ? }
public void println(long x) {
? ? ? ? if (getClass() == PrintStream.class) {
? ? ? ? ? ? writeln(String.valueOf(x));
? ? ? ? } else {
? ? ? ? ? ? synchronized (this) {
? ? ? ? ? ? ? ? print(x);
? ? ? ? ? ? ? ? newLine();
? ? ? ? ? ? }
? ? ? ? }
? ? }
public void println(char[] x) {
? ? ? ? if (getClass() == PrintStream.class) {
? ? ? ? ? ? writeln(x);
? ? ? ? } else {
? ? ? ? ? ? synchronized (this) {
? ? ? ? ? ? ? ? print(x);
? ? ? ? ? ? ? ? newLine();
? ? ? ? ? ? }
? ? ? ? }
? ? }
public void println(String x) {
? ? ? ? if (getClass() == PrintStream.class) {
? ? ? ? ? ? writeln(String.valueOf(x));
? ? ? ? } else {
? ? ? ? ? ? synchronized (this) {
? ? ? ? ? ? ? ? print(x);
? ? ? ? ? ? ? ? newLine();
? ? ? ? ? ? }
? ? ? ? }
? ? }
等等等等~這里就不一一列舉了!
總結(jié) System.out.println()就是:類調(diào)用對象,對象調(diào)用方法!
開拓視野:
System.out.print();與System.out.println(); 的區(qū)別
public class Text {
? ? public static void main(String[] args) {
? ? ? ? System.out.print('a');
? ? ? ? System.out.print('b');
? ? ? ? System.out.println('c');
? ? ? ? System.out.println('d');
? ? }
}
運行結(jié)果:
abc
d
System.out.print();輸出結(jié)果不能換行,System.out.println();輸出結(jié)果進行換行。