什么时候在构造函数之外的初始化调用? [英] When are initializations outside a constructor called?

查看:155
本文介绍了什么时候在构造函数之外的初始化调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

  class MyObject 
{
Object object1 = new Object();
Object object2;

public MyObject()
{
object2 = new Object();
}

public MyObject(Object object2)
{
this.object2 = object2;
}

public MyObject(Object object1,Object object2)
{
this.object1 = object1;
this.object2 = object2;
}
}

code> get初始化? object2 之后, object2



如果我的构造函数与 object1 的全局定义冲突,会发生什么?在第三个构造函数中。哪个值 object take?



这不会引起任何问题,有点好。

解决方案


  • 变量被初始化为其类型的默认值(0,null等)


  • 首先调用超类构造函数。如果超类构造函数调用此类中重写的任何虚方法,则无论任何变量初始化器或构造函数体中的初始化,覆盖都将看到默认值。



$ b


$ b

所以如果你在构造函数体中改变一个变量的值,变量初始值设置的任何值都会被覆盖。 (当然,以前的值可能用于其他链接构造函数等)



请参阅第12.5节的JLS了解详情。


Suppose I have

class MyObject
{
    Object object1 = new Object();
    Object object2;

    public MyObject()
    {
        object2 = new Object();
    }

    public MyObject(Object object2)
    {
        this.object2 = object2;
    }

    public MyObject(Object object1, Object object2)
    {
        this.object1 = object1;
        this.object2 = object2;
    }
}

When does object1 get initialized? Before object2, after object2, depends?

What happens if I have a constructor that conflicts with the global definition of object1, e.g. in the third constructor above. Which value does object take?

This isn't causing me any problems but I just wanted to understand the language a bit better. I like to know these little things so that I could potentially make use of them later on.

解决方案

  • The variables are initialized to the default values for their type (0, null etc)

  • First the superclass constructor is called. If the superclass constructor calls any virtual methods overridden in this class, the override will see the default values, regardless of any variable initializers or initialization in the constructor body.

  • Then variable initializers are executed.

  • Then the constructor body is executed.

So if you change the value of a variable within the constructor body, any value set by the variable initializer will be overwritten. (The previous value could have been used in other chained constructors etc, of course.)

See section 12.5 of the JLS for more details.

这篇关于什么时候在构造函数之外的初始化调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆