Re: question about assigning null to a reference object
Farcus Pottysquirt wrote:
....
should have done the try...catch in the main program, not the method. My
question now is, doesn't the c.showAll() method exist even after the
reference object has been assigned to null? If so, why is the NPE not
catchable in the method?
References and objects are different things in Java. A reference is
either null, or a pointer to some object of suitable class for the
pointer's type. Instance methods belong to objects, not references.
The object formerly pointed to by c may or may not still exist. There
are no references to it, so the garbage collector could choose to
destroy it at any moment. If it still exists, arguably it still has a
showAll() method, but with no references it would be a very abstract
form of existence.
If you added "Book d = c;" before the "c = null;", then d would
reference that object, and you could call d.showAll().
Once you do "c = null;" c no longer points to any object, and any
attempt to use c to access any member, including showAll, will cause a
NullPointerException without performing the access.
Patricia