Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Field definition  RSS feed

 
Sen George
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the concept of a field associated with a class? Can it be compared to a static constant?

An example is 'out' in java.lang.System.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sen George:
What is the concept of a field associated with a class? Can it be compared to a static constant? ...

It only needs to be static. In fact, that's what "static" means: Associated with the class itself rather than any particular instance of that class.

To be associated with the class, there is no need for the field to be "constant." (Although if a value is constant, it often makes sense for it to be static, so that the same value isn't duplicated in every instance.)
 
Sen George
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply. But I still can't reason out the call 'System.out.println'.

I was expecting the println method to be part of the System class. In other words, how is the construct [Field.method] justified in Java?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sen George:
...how is the construct [Field.method] justified in Java?

The "Field" references an object, and the method is called on that object.

If you check the API documentation for System, you will see that "out" is a static variable referencing an instance of PrintStream. Therefore, "System.out" references a PrintStream object.

Now if you check the API documentation for PrintStream, you will see that "println" is a method that is heavily overloaded to accept a variety of types (primitives, Objects, Strings, char arrays, or even no arguments at all).

So when you call System.out.println(x), you are passing x to the println method of a PrintStream instance, referenced by the static variable "out" in the System class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!