• Post Reply Bookmark Topic Watch Topic
  • New Topic

Flow of program and anynomous objects  RSS feed

 
Travis Roberts
Ranch Hand
Posts: 54
C++ Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java Ranch:

I am preparing for a test and as a preparation was given one of the following questions:



The answer I chose was correct, the program outputs 5. But I had a couple of questions for clarification.

If the main driver class was longer, am I right to assume that the anonymous class on line 4 becomes eligible for garbage collection starting on the next line, line 5?

Also, I am uncertain as to why the toString method prints anything at all since it was not called? I tested by adding another method below that one which returns an integer



And that printInt method did not print anything??
 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Travis Roberts wrote:
If the main driver class was longer, am I right to assume that the anonymous class on line 4 becomes eligible for garbage collection starting on the next line, line 5?

Anonymous classes are a very different thing. But yes, the anonymous object would immediately become eligible for garbage collection.

Travis Roberts wrote:
Also, I am uncertain as to why the toString method prints anything at all since it was not called? I tested by adding another method below that one which returns an integer

When an object is passed to println, the return value of its toString method is what gets printed. All classes have a default toString method, but you can override this method as shown in the problem.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More precisely, the println() method is heavily overloaded and when its argument is anything other than a String, the argument is passed to String.valueOf() which in turn calls the argument's toString() method. When the argument to println() is a String, it is just written out directly. Note that when the argument is a primitive value such as int, long, double, etc. String.valueOf(), which is also overloaded, will call the corresponding wrapper class toString() method.
 
Travis Roberts
Ranch Hand
Posts: 54
C++ Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!