We can access a method of a class simply using its referrence name eg:CharStack stack1 = new CharStack()is the object instantiated stack1.push() (or) CharStack.push() if method is static
But, why do we use two (.)dot operators in order to access println method can't we just say System.println("hello")
The "out" object is of the PrintStream class .System class extends Object class .System cannot be instantiated,does it mean it is a static class??To whom does PrintStream class belong to and why dont we use PrintStream.println("hello") or just out.println("hello") as out is an object of class PrintStream.
Everyting is very confusing can anybody help me clear my doubts please Thanks in advance!!!
"out" is a public, static member variable of the System class. You don't see too many of these as they're generally considered bad style. It's an instance of PrintStream, as you said -- a useful instance, connected to the program's standard output stream, that's available as soon as your program starts.
println() is an instance method of PrintStream, so that you need an instance of PrintStream to call it. "System.out" is such an instance, and so "System.out.println()" is a call to that method on that object.
Thanks for ur reply but I feel more confused now!! you said ""out" is a public, static member variable of the System class" and also that "It's an instance of PrintStream" that creates a doubt that does out belong to PrintStream or does it belong to System and what is the relation between PrintStream and System class?? Is this code legal-->
> you said ""out" is a public, static member variable of the System class" > and also that "It's an instance of PrintStream" that creates a doubt that > does out belong to PrintStream or does it belong to System and what is the > relation between PrintStream and System class??
out is a public and static member variable of class System. The type of the member variable is PrintStream - so, it is an instance of class PrintStream.
So I'd say, it belongs to class System. There is no relation between class System and class PrintStream, other than that System has a member variable of type PrintStream.
If you're confused the terms member variable and instance, you'll have to have a good look at your Java textbook or The Java Tutorial again.
No, because class PrintStream does not have a no-arguments constructor. So the first line of that will give you a compiler error.
> Also I found that I cannot compile the legal code you gave without including > the import java.io.* statement but I can do so for System.out.println("") > without the import statement.
Because Java needs to know where to get class PrintStream from (it's in the package java.io). When you're jsut using System.out.println(...), you're not referring to the classname PrintStream, so you don't need to import it.