This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I am flipping through the Exception Handling chapter in Head First Java and I've come across some code that I don't quite understand.
How can java assign a result of a reference variable method call to a reference variable of type Foo when an object of type Foo hasn't been created? I know it is a stupid question considering I've gotten this far in the book. I just haven't seen it used like this so far.
how do you know it's not defined as something like
this sort of thing is common in what are called Factories. A factory is an object that creates other objects. So, you may have a PizzaParlorFactory (to steal from Head First Design Patterns) that returns PizzaParlors:
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree with Fred. Please provide full code snippet.
How can java assign a result of a reference variable method call to a reference variable of type Foo when an object of type Foo hasn't been created?
Further more it could be null also. It's not compulsory that it has to return an object only.
Joined: Oct 14, 2008
The book doesn't actually define what doRiskyThing is. It is just a small code snippet.
Joined: Aug 16, 2007
Then you can assume reference variable can hold,
2) Object of same type as reference type
3) Object of child class of the reference type
4) If reference type is interface then it can hold any object that implements that interface.
What do you say? Am I missing anything?
Joined: Oct 14, 2008
I just thought that for a reference variable to hold anything, it must be "newed" up. I'm assuming that in this example, they mean to show that Foo f is being "newed" up in the doRiskyStuff method and is then passed back and assigned to f.
There probably is a 'new' somewhere, but you may never see it. it's common to use code written by other parties that return object references. you won't ever have access to the source code, so you won't know what they're doing.
when you get into interfaces, you may not even know why specific kind of object it is - you'll just know the kind of interface, which is good enough (in fact, it's often PREFERRED).
subject: Assigning method results to a reference variable