How does System.out.println() method work?
What I see is that "out" is a static class variable in System class of type PrintStream. ( from the API )...
Since println() found in PrintStream class is not a static method, you need an object to call its method. ( You can not just say PrintStream.println("Hello World..")...
System class has a reference (PrintStream out) in its fields. But where is the object?
I will answer my own question:
Code:
package myPackage;
public class MyPrintStreamClass
{
public void bark()
{
System.out.println("Bark!");
}
}
Code:
package myPackage;
public class MySystemClass
{
public static final MyPrintStreamClass outt = new MyPrintStreamClass();
}
Code:
package myPackage;
public class MyTestClass
{
public static void main(String[] args)
{
MySystemClass.outt.bark();
}
}
( This is for discussion and helping purposes. )
//
You can also do something like this:
Code:
PrintStream consoleOutputStream = new PrintStream(System.out);
consoleOutputStream .println("Hello");
What you are doing here is:
Defining a variable pointing to a PrintStream object,
that is a copy of the object that is in System Class.
So the field out in System class, which is type of PrintStream is already pointing to an Object.
Re: How does System.out.println() method work?
Quote:
Originally Posted by
fatabass
You can also do something like this:
Code:
PrintStream consoleOutputStream = new PrintStream(System.out);
consoleOutputStream .println("Hello");
What you are doing here is:
Defining a variable pointing to a PrintStream object,
that is a copy of the object that is in System Class.
It's not a copy.
It is a (pointless) wrapping of the existing PrintStream object from System inside of another PrintStream object.
Re: How does System.out.println() method work?
So consoleOutputStream is referencing a PrintStream object, that we have created by saying new PrintStream().
and what we are passing into the PrintStream() constructor is: System.out
Which is a reference itself, that is pointing to an already existing PrintStream Object.
which means:
consoleOutput --> A PrintStreamObject(System.out --> Already Existing Object)
Re: How does System.out.println() method work?
Re: How does System.out.println() method work?