什么是Java中的对象字段初始化和构造函数顺序 [英] What is object field initialization and constructor order in Java

查看:86
本文介绍了什么是Java中的对象字段初始化和构造函数顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天早些时候在代码中结束了以下场景(我承认有点奇怪,我已经重构了)。当我运行单元测试时,我发现在超类构造函数运行时没有设置字段初始化。我意识到我并不完全理解构造函数/字段初始化的顺序,所以我希望有人向我解释这些发生的顺序。

I ended up the following scenario in code earlier today (which I admit is kinda weird and I have since refactored). When I ran my unit test I found that a field initialization was not set by the time that the superclass constructor has run. I realized that I do not fully understand the order of constructor / field initialization, so I am posting in the hopes that someone explain to me the order in which these occur.

class Foo extends FooBase {
    String foo = "foobar";

    @Override
    public void setup() {
        if (foo == null) {
            throw new RuntimeException("foo is null");
        }
        super.setup();
    }
}

class FooBase {
    public FooBase() {
        setup();
    }

    public void setup() {

    }
}

@Test
public void testFoo() {
    new Foo();
}

JUnit的缩写回溯如下,我想我期望$ Foo。 < INIT>设置foo。

The abbreviated backtrace from JUnit is as follows, I guess I expected $Foo.<init> to set foo.

$Foo.setup
$FooBase.<init>
$Foo.<init>
.testFoo


推荐答案

是的,用Java(例如,与C#不同,字段初始值设定项在超类构造函数之后被称为。这意味着在执行字段初始值设定项之前,任何来自构造函数的重写方法调用都将被称为

Yes, in Java (unlike C#, for example) field initializers are called after the superclass constructor. Which means that any overridden method calls from the constructor will be called before the field initializers are executed.

排序为:


  • 初始化超类(递归调用这些步骤)

  • 执行字段初始化程序

  • 执行构造函数体(在任何构造函数链接之后,已在步骤1中发生)

基本上,调用它是个坏主意构造函数中的非最终方法。如果您打算这样做,请清楚地记录 very ,以便覆盖该方法的任何人都知道在执行字段初始化程序(或构造函数体)之前将调用该方法。

Basically, it's a bad idea to call non-final methods in constructors. If you're going to do so, document it very clearly so that anyone overriding the method knows that the method will be called before the field initializers (or constructor body) are executed.

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

这篇关于什么是Java中的对象字段初始化和构造函数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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