Question

When we the statement System.out.println() in java to output something on screen. In this statement System is the class, out is the object of that class, println() is the method of that class.

When we declare an instance or object of, suppose, class A in class B, then following syntax is used, A object;, and then if there are any methods of the class, which have been declared as public, then in following syntax the methods are called, object.method(argument).

Now my question is that why we can't declare the object, out, of the class, System, in the following syntax, System out = new System();.

Was it helpful?

Solution

In this statement "System" is the class, "out" is the object of that class,

No, out is a static field within System. It's a field which returns a reference to a PrintStream. It's not an instance of System. So you can use:

PrintStream stream = System.out;
stream.println("Foo");

(It's important to distinguish between classes, objects, fields, references etc by the way. Taking some time to get the terminology right can really help you understand it correctly.)

OTHER TIPS

System has a private constructor that you cannot access:

64    private System() {
65    }

(source)

If by System out = new System() you're trying to reassign System.out... well you can't do that either, since out is final and hence cannot be reassigned after it has been initialized (not to mention it's of type PrintWriter, and not System).

You're misunderstanding how the Java syntax works. In System.out, System is a class. The dot operator means that out is a member of that class (in this case a variable, not a method, because there are no parentheses), not an instance of it. out is an object of type PrintStream, and you could in fact create new instances of PrintStreams (such as by opening files for writing).

System happens to be a special Java class that you can't instantiate yourself. For most classes, you can use the syntax you described: Car myCar = new Car();

out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final.

This gets instantiated during startup and gets mapped with standard output console of the host.

See how it works

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top