加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在构造函数结束之前如何引用/处理“this”?

发布时间:2020-12-14 23:35:25 所属栏目:Java 来源:网络整理
导读:我想到这个问题的具体用法如下,但它更加普遍. 我有一个自定义的JFrame类,它也可以作为其组件的ActionListener.所以我的构造函数看起来像下面这样: private JButton myButton;public MyCustomFrame() { super(); myButton.addActionListener(this); // ... m
我想到这个问题的具体用法如下,但它更加普遍.

我有一个自定义的JFrame类,它也可以作为其组件的ActionListener.所以我的构造函数看起来像下面这样:

private JButton myButton;

public MyCustomFrame() {
    super();
    myButton.addActionListener(this);
    // ... more stuff
}

我的问题是,这在幕后实际上是如何运作的?如果构造函数是“创建”由此引用的对象,那么在构造函数返回之前如何使用它?代码编译和工作完全正常(据我所知),所以对象必须已经“存在”在某种意义上,但我担心这可能会导致无法预料的问题.传递对addActionListener()的“部分构造”引用是否存在任何危险(或者通常只使用它执行任何逻辑)?或者是否有一些让我安全的幕后魔术?

例如,那些没有默认值但必须由构造函数提供的东西呢?如果我有私有的最终字符串SOME_VALUE;声明,我明白这应该默认为null,但是在构造函数中为常量提供值之前,该对象不应该完全形成.那么参考,尽管是最终的,可能会有变化的价值?

解决方法

该Java语言规范指定了 instance creation的步骤

[…]

Next,space is allocated for the new class instance. If there is
insufficient space to allocate the object,evaluation of the class
instance creation expression completes abruptly by throwing an
OutOfMemoryError.

The new object contains new instances of all the fields declared in
the specified class type and all its superclasses. As each new field
instance is created,it is initialized to its default value (§4.12.5).

Next,the actual arguments to the constructor are evaluated,
left-to-right. If any of the argument evaluations completes abruptly,
any argument expressions to its right are not evaluated,and the class
instance creation expression completes abruptly for the same reason.

Next,the selected constructor of the specified class type is invoked.
This results in invoking at least one constructor for each superclass
of the class type. This process can be directed by explicit
constructor invocation statements (§8.8) and is described in detail in
§12.5.

因此,当调用构造函数(这是一个方法)时,您的实例存在默认值.

对于最终字段,如果您尝试访问它们,它们似乎也是默认的.例如

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.如果我能找到它,我会马上回到JLS条目.

我找不到更具体的东西,然后是上面的内容.也许在4.12.4. final Variables

A final variable may only be assigned to once.

您可以认为默认初始化将值设置为0或null,并且赋值会更改它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读