Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how does System.out refer to PrintStream class?

Tags:

java

I'm a beginner learning Java with some knowledge of C++, and the System.out.println(); is confusing me right now. So System is the class, out is a variable that can call a method?? According to: http://journals.ecs.soton.ac.uk/java/tutorial/getStarted/application/objects.html out is a class variable, and a variable is a storage location in the computer memory that has a type name and content. It's not an object like string that can use methods like .getLength(). The way the website explains it is that out refers to an instance of PrintStream class, but how?

like image 226
Freeman Lou Avatar asked Jan 16 '23 02:01

Freeman Lou


2 Answers

It's not an object

This is where your reasoning is going wrong. System.out is (a reference to) an object.

The type of the reference is PrintStream, as documented in the Javadoc. This means that you can call PrintStream's methods on System.out, e.g.:

System.out.println();
like image 87
NPE Avatar answered Jan 17 '23 17:01

NPE


out doesn't call a method : out is a variable holding an object (an instance of PrintStream) on which you can call a method.

For example :

System.out.println("hey!");

You could also do

void print(PrintStream ps, Object o) {
    ps.println(o);
}
...
print(System.out, "hey!");
like image 33
Denys Séguret Avatar answered Jan 17 '23 16:01

Denys Séguret