Re: Constructor
Philipp wrote:
If I write:
<code>
MyClass object = new MyClass(someArgument);
object.doStuff();
</code>
Do I have a guarantee that object is not null when I call doStuff?
Yes.
'new' cannot return 'null'.
Or is there a possible execution path which reaches .doStuf() [sic] with object
being null?
Bo Vance wrote:
No such guarantee.
try {
MyClass object =
new MyClass(someArgument);
object.doStuff();
} catch (someE e) {
some handling
} // guaranteed object.doStuff() won't be called if
// new MyClass(someArgument) throws.
See the JLS subsection:
15.9.4 Run-time Evaluation of Class Instance Creation Expressions
<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.9.4>
This doesn't answer the OP's question. That's how the execution might *not*
reach 'doStuff()', but they asked how it might *reach* 'doStuff()' with
'object' not assigned (or assigned 'null').
For that read the JLS on "definite assignment". It gets an entire chapter.
<http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html>
There are ways to reach a reference without it being assigned, basically
involving failure to deal with exceptions.
Foo foo; // I hate including 'Class' or 'object' in identifiers
try
{
foo = new Foo();
}
catch ( Exception exc )
{
// completely fail to handle exc
}
foo.doStuff(); // error
--
Lew