-4

As far as i know it is not true then how come out variable of System class

 final static PrintStream out = null;

can refer to the print method of the PrintStream class in System.out.print();

public void print(Object obj) {
    write(String.valueOf(obj));
}

PS: This question is not same as What's the meaning of System.out.println in Java? or any related one.

  • there is no relation between the two code snippets. – luk2302 Mar 25 '18 at 11:09
  • In System.out.print() or in system.out.println() methods out variable is used to refer to print method – Krishnan Mishra Mar 25 '18 at 11:11
  • you are mixing up all sorts of statements and terminology here. You *obviously* do not yet understand what System.out.println means / does. – luk2302 Mar 25 '18 at 11:12
  • 2
    out is an instance of PrintStream so it can use PrintStream’s instance methods. – cpp beginner Mar 25 '18 at 11:12
  • You don't seem to understand what `static` means. You might want to see if one of the answers in [What does the 'static' keyword do in a class?](https://stackoverflow.com/q/413898) or [In laymans terms, what does 'static' mean in Java?](https://stackoverflow.com/q/2649213) answers your question, or read up about `static` further elsewhere. – Bernhard Barker Mar 25 '18 at 11:16
  • out is having static keyword so isn't it a static variable of Printstream type? – Krishnan Mishra Mar 25 '18 at 11:16
  • 1
    out is a static member of the System class. – cpp beginner Mar 25 '18 at 11:21

1 Answers1

0

The phrase "static members cannot refer to instance methods" is an oversimplification that causes confusion.

The actual restriction is that static methods and static field initializers cannot invoke instance methods without providing a reference to a specific object for the invocation.

In case with static System.out there is no issue at all, because print is invoked directly on the PrintStream object, which happens to be stored as a static field of some other class, in this case, java.lang.System. There is no difference between

System.out.print("hello");

and

PrintStream myOutput = System.out;
myOutput.print("hello");
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523