Java – how to reference / handle “this” before the constructor ends?

I think the specific usage of this problem is as follows, but it is more common

I have a custom JFrame class, which can also be used as the actionlistener of its component So my constructor looks like this:

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 to "create" the object referenced by this, how do you use it before the constructor returns? The code compiles and works perfectly (as far as I know), so the object must already "exist" in a sense, but I'm worried that this may lead to unexpected problems Is there any danger in passing a "partially constructed" reference to addactionlistener() (or is it usually used only to perform any logic)? Or is there some magic behind the scenes to keep me safe?

For example, what about things that have no default values but must be provided by constructors? If I have a private final string, some_ VALUE; Declaration, I understand that this should default to null, but the object should not be fully formed until a constant value is provided in the constructor So reference, although final, may have changing value?

Solution

The Java language specification specifies the steps for instance creation

Therefore, when you call the constructor, which is a method, your instance has a default value

For the final fields, they also seem to be the default if you try to access them for example

public class Driver {

    public static void main(String[] args) {
        new Driver();
    }

    final int value;

    public Driver() {
        print(this);
        value = 3;
    }

    static void print(Driver driver) {
        System.out.println(driver.value);
    }

}

0.0 will be printed If I can find it, I'll go back to the JLS entry immediately

I can't find anything more specific, and then the content above Maybe on April 12 4. final Variables

You can assume that the default initialization sets the value to 0 or null, and the assignment changes it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>