简体   繁体   中英

Is 'println()' a static member function of PrintStream class or instance member function?

Here:

System.out.println("Hi, this is frist program");

Is println() a static member function of PrintStream class or instance member function?

As told by my teacher : that when there is dot ( . ) after class name then definitely we are trying to access the static member of the class.

As here out is static reference variable and it has reference of PrintStream class. So my question is that is the println() function has necessarily to be a static member function?

No, println is an instance method of the PrintStream class. It is out that is a static member of the System class.

System.out
      ^--^
        static member of the class System, returns a PrintStream instance

System.out.println(...)
          ^------^
            instance method of PrintStream

out is declared as

public static final PrintStream out

in the class System , so it is a static member and you access it with System.out (refer to this question for the final modifier).

println() is an instance method of the PrintStream class declared as

public void println()

No, println is an instance method of PrintStream , as you can see in the Javadoc of PrintStream .

void java.io.PrintStream.println(String x)

System.out gives you a reference to a PrintStream instance for which println is executed.

println() is a non static (instance) member function of PrintStream class.

out is a static reference to an object of type PrintStream , inside System class.

out is a reference, out.prinln() refers to the instance method of out . In this case out is also a static member of another class, but this doesn't make any difference to the println() method

It's an instance method.

System.out is a static reference to a PrintStream instance. https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#out and this provides multiple overloaded versions if println https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(java.lang.String)

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