As part of my studies I am taking an online course targeting certification but this is a pretty elementary question so I put it here. On the subject of instantiating objects....they wanted to show an example of how ONE LINE could 1)declare a variable, 2) instantiate and initialize and object of a certain type, 3) call a method of that class, and finally 4) return the result back to the initial variable.
Here is the line (changed to make it mine....):
String name = new Account("Bob Ruth","1234 Any Street").getName();
for now, assume that the class is properly declared.... I just grabbed this one line. The line itself I can understand clear as a bell. That's not what I am curious about.
I personally see no explicit reference variable created to hold the reference to the new object instantiated. My little "pea brain" makes me think that the object is instantiated, initialized, and lives long enough to regurgitate the name back to the "name" variable, and would then be completely abandoned and left as garbage collection fodder. I can live with it if that IS the case, I just want to make sure that I am not missing something in the mechanics here.
Thanks a million, Bob
SCJP - 86% - June 11, 2009
Yep, that's the case; unless the Account object does something in its constructor or getName() method to store a reference to itself, somewhere, then it's not referenced and can be immediately collected.
I realize that I can go prototype this as well as the next guy but, just for thought, would this work?
Account myAccount; String name = (myAccount = new Account("Bob Ruth","1234 Any Street")).getName();
my thinking here is that doing a myAccount = and enclosing that in a new set of parens, that the new object ref would get put in myAccount.... AND that the (myAccount = new Account(yadda yadda yadda)) would STILL evaluate to the new object reference so the .getName should still work..... I think.....
by the way.... the mentor at the training site emailed me back and said the same thing that I thought and that you said. I must not be as dumb as I look!!!
author and iconoclast
i'd say if you're going to do that, to just do this:
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Jun 04, 2007
I couldnt agree with you more .... I dont code in that style of jamming it all in as few lines as possible... I'd rather have it readable because I may be the slob back in here reading it again 2 or 3 years from now!!!