The specific use where I thought of this problem is as follows, but it's much more generalized.
I have a custom JFrame
class which also serves as an ActionListener
for its components. So my constructor looks something like the following:
private JButton myButton;
public MyCustomFrame() {
super();
myButton.addActionListener(this);
// ... more stuff
}
My question is, how does this actually work behind the scenes? If the constructor is what "creates" the object which is referenced by this
, how can I use this
before the constructor has returned? The code compiles and works perfectly fine (as far as I can tell), so the object must already "exist" in some sense, but I'm concerned that this may cause unforeseen issues. Is there any danger in passing a "partially constructed" reference to addActionListener()
(or just performing any logic with it in general)? Or is there some behind-the-curtain magic happening that keeps me safe?
For example, what about things which don't have default values and must be supplied by the constructor? If I have private final String SOME_VALUE;
declared, I understand that this should default to null
, but the object isn't supposed to be fully formed until the constant is supplied a value within the constructor. So would the reference, despite being final, possibly have changing values?