I'm doing a Java course. Having gone through the use of accessor
(setter and getter) methods for instance variables, it goes on to say:
"For reasons that cannot be elaborated upon here, it is safer, where
possible, to initialise instance variables directly in a constructor
rather than using setter messages."
Can anyone offer a simple explanation for this?
> I'm doing a Java course. Having gone through the use of accessor
> (setter and getter) methods for instance variables, it goes on to say:
[quoted text clipped - 4 lines]
>
> Can anyone offer a simple explanation for this?
I read this book, "Java Puzzlers", which said it was a bad idea to have
your constructors call methods which can be overridden. To prevent methods
from being overridden, you can either mark them as being "final" or as being
"private". They explained why it was a bad idea, giving a code example that
led to a hard to track bug, but I can't remember what it was now. It
certainly made sense at the time, when I read it.
So I'm assuming this is what your book is referring to as well, since
presumably your setter methods are not going to be private, and they may
possibly be non-final.
- Oliver
Ian Shef - 30 Mar 2006 20:29 GMT
>> I'm doing a Java course. Having gone through the use of accessor
>> (setter and getter) methods for instance variables, it goes on to say:
[quoted text clipped - 12 lines]
> code example that led to a hard to track bug, but I can't remember what
> it was now. It certainly made sense at the time, when I read it.
<snip>
The setter method of the derived class has access to the data of the
derived class. However, during contruction of an object of the derived
class, this data has not yet been initialized when the base class object is
constructed and calls the setter method of the derived class.
"Thinking in Java", 3rd ed. Revision 4.0, Chapter 7, makes the point more
clearly than I can (and provides an example that I won't reproduce here:
"Conceptually, the constructor’s job is to bring the object into existence
(which is hardly an ordinary feat). Inside any constructor, the entire
object might be only partially formed—you can know only that the base-class
objects have been initialized, but you cannot know which classes are
inherited from you. A dynamically bound method call, however, reaches
“outward” into the inheritance hierarchy. It calls a method in a derived
class. If you do this inside a constructor, you call a method that might
manipulate members that haven’t been initialized yet—a sure recipe for
disaster."

Signature
Ian Shef 805/F6 * These are my personal opinions
Raytheon Company * and not those of my employer.
PO Box 11337 *
Tucson, AZ 85734-1337 *