且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是Java中的对象字段初始化和构造函数顺序

更新时间:2022-12-13 14:06:40

是的,用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节了解更多详情。