当从super()运行方法时,为什么字段没有初始化为非默认值? [英] Why aren't fields initialized to non-default values when a method is run from super()?

查看:133
本文介绍了当从super()运行方法时,为什么字段没有初始化为非默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定花了一个多小时试图找出出现意外行为的原因。我最终意识到没有像我期望的那样设置场地。在耸耸肩并继续前进之前,我想了解为什么会这样运作。



在运行下面的例子中,我希望输出为真,但是这是假的。其他测试表明我总是得到任何类型的默认值。

 公共类ClassOne {

public ClassOne(){
fireMethod();
}

protected void fireMethod(){
}

}

公共类ClassTwo扩展ClassOne {

boolean bool = true;

public ClassTwo(){
super();
}

@Override
protected void fireMethod(){
System.out.println(bool =+ bool);
}

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

输出:

  bool = false 


解决方案



  boolean bool = true; 

public ClassTwo(){
super();
}



<相同< pre class =lang-java prettyprint-override> boolean bool;

public ClassTwo(){
super();
bool = true;
}

编译器自动在构造函数中移动字段初始化(在超级构造函数之后)通过隐式或显式调用。



由于布尔字段默认值为 false ,因此 super()被调用(因此 ClassOne() fireMethod()) , bool 尚未设置为 true



< hr>

有趣的事实:以下构造函数

  public ClassTwo(){
super();
fireMethod();
}

将被理解为

  public ClassTwo(){
super();
bool = true;
fireMethod(); JVM的
}

,因此输出

  bool = false 
bool = true


I must have spent over an hour trying to figure out the reason for some unexpected behavior. I ended up realizing that a field wasn't being set as I'd expect. Before shrugging and moving on, I'd like to understand why this works like this.

In running the example below, I'd expect the output to be true, but it's false. Other tests show that I always get whatever that type default value is.

public class ClassOne {

    public ClassOne(){
        fireMethod();
    }

    protected void fireMethod(){
    }

}

public class ClassTwo extends ClassOne {

    boolean bool = true;

    public ClassTwo() {
        super();
    }

    @Override
    protected void fireMethod(){
        System.out.println("bool="+bool);
    }

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

output:

bool=false

解决方案

boolean bool = true;

public ClassTwo() {
    super();
}

is identical to

boolean bool;

public ClassTwo() {
    super();
    bool = true;
}

The compiler automatically moves the fields initializations within the constructor (just after the super constructor call, implicitly or explicitly).

Since a boolean field default value is false, when super() is called (and thus ClassOne() and fireMethod()), bool hasn't been set to true yet.


Fun fact: the following constructor

public ClassTwo() {
    super();
    fireMethod();
}

will be understood as

public ClassTwo() {
    super();
    bool = true;
    fireMethod();
}

by the JVM, and the output will thus be

bool=false
bool=true

这篇关于当从super()运行方法时,为什么字段没有初始化为非默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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