-2

Just started learning Java, through the "hello world" app, k learned about the object System.out.

Out is an object, but to use it, we have to write system in front of it. It's obvious and my book says that out belongs to system class.

But later in the book, my book says out also belongs to PrintStream class. That is what enable us to use println methods because they both belong to PrintStream class.

I am confused what class does out belong to?

Also, is it just a convention that for objects like out, we have to write the class as well whenever we use it. For something like;

String greeting = "Hello, World!"; If we want to use .length() method which I guess also belongs to string class, we DONT write: int n=String.greeting.length()

Instead, it's just: int n=greeting.();

  • You should probably read up on java and inheritance: http://beginnersbook.com/2013/03/inheritance-in-java/ – Robert Moskal May 10 '16 at 00:28
  • `String.greeting.length()` doesn't make sense, because `String` has no `greeting` field. You write `System` in front of `out.println()` because the class `System` contains the static field that holds `stdout`. – Natecat May 10 '16 at 00:32
  • @RobertMoskal , I didn't know anything of inheritance. The topic is 8 chapter after the one I am on. I don't want to read it without reading the things in between, just in case I miss something important that impedes my understanding. – most venerable sir May 10 '16 at 00:34
  • Because the question got closed while I was answering here's what I had in two comments to get over the text limitations: The `System` class (https://docs.oracle.com/javase/7/docs/api/java/lang/System.html) in Java contains a `PrintStream` object that is called `out`. In other words, it is an instance (a created object) of the class `PrintStream` that is owned by the class `System`. `PrintStream` objects (https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html) have a method called print inside them. – gadu May 10 '16 at 01:01
  • What this means is if you had a `PrintStream` object, u could call print on it regardless of what u named it: `PrintStream myPrintStream = [code to initialize it]; myPrintStream.print();` The creators of Java just happened to name the `PrintStream` in `System` 'out'. Now, maybe confusingly, `PrintStream` has its own field called 'out' which basically tells the `PrintStream` where to output the text being given to it. In the inner Java code, what Im pretty sure happens is that the 'out' field of the `PrintStream` that belongs to the `System` object is set to print to the console – gadu May 10 '16 at 01:04

1 Answers1

1

out is a (static) member variable of class System.
It is an instance of class PrintStream.

class Foo {
    String x;
}

x is a string. It is a member of class Foo. Same idea.

djechlin
  • 59,258
  • 35
  • 162
  • 290